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 static cl::opt<bool> 103 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden, 104 cl::desc("Allow AArch64 SLI/SRI formation"), 105 cl::init(false)); 106 107 // FIXME: The necessary dtprel relocations don't seem to be supported 108 // well in the GNU bfd and gold linkers at the moment. Therefore, by 109 // default, for now, fall back to GeneralDynamic code generation. 110 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration( 111 "aarch64-elf-ldtls-generation", cl::Hidden, 112 cl::desc("Allow AArch64 Local Dynamic TLS code generation"), 113 cl::init(false)); 114 115 static cl::opt<bool> 116 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden, 117 cl::desc("Enable AArch64 logical imm instruction " 118 "optimization"), 119 cl::init(true)); 120 121 /// Value type used for condition codes. 122 static const MVT MVT_CC = MVT::i32; 123 124 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM, 125 const AArch64Subtarget &STI) 126 : TargetLowering(TM), Subtarget(&STI) { 127 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so 128 // we have to make something up. Arbitrarily, choose ZeroOrOne. 129 setBooleanContents(ZeroOrOneBooleanContent); 130 // When comparing vectors the result sets the different elements in the 131 // vector to all-one or all-zero. 132 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 133 134 // Set up the register classes. 135 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass); 136 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass); 137 138 if (Subtarget->hasFPARMv8()) { 139 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass); 140 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass); 141 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass); 142 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass); 143 } 144 145 if (Subtarget->hasNEON()) { 146 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass); 147 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass); 148 // Someone set us up the NEON. 149 addDRTypeForNEON(MVT::v2f32); 150 addDRTypeForNEON(MVT::v8i8); 151 addDRTypeForNEON(MVT::v4i16); 152 addDRTypeForNEON(MVT::v2i32); 153 addDRTypeForNEON(MVT::v1i64); 154 addDRTypeForNEON(MVT::v1f64); 155 addDRTypeForNEON(MVT::v4f16); 156 157 addQRTypeForNEON(MVT::v4f32); 158 addQRTypeForNEON(MVT::v2f64); 159 addQRTypeForNEON(MVT::v16i8); 160 addQRTypeForNEON(MVT::v8i16); 161 addQRTypeForNEON(MVT::v4i32); 162 addQRTypeForNEON(MVT::v2i64); 163 addQRTypeForNEON(MVT::v8f16); 164 } 165 166 if (Subtarget->hasSVE()) { 167 // Add legal sve predicate types 168 addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass); 169 addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass); 170 addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass); 171 addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass); 172 173 // Add legal sve data types 174 addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass); 175 addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass); 176 addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass); 177 addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass); 178 179 addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass); 180 addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass); 181 addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass); 182 addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass); 183 addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass); 184 addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass); 185 186 for (auto VT : { MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64 }) { 187 setOperationAction(ISD::SADDSAT, VT, Legal); 188 setOperationAction(ISD::UADDSAT, VT, Legal); 189 setOperationAction(ISD::SSUBSAT, VT, Legal); 190 setOperationAction(ISD::USUBSAT, VT, Legal); 191 setOperationAction(ISD::SMAX, VT, Legal); 192 setOperationAction(ISD::UMAX, VT, Legal); 193 setOperationAction(ISD::SMIN, VT, Legal); 194 setOperationAction(ISD::UMIN, VT, Legal); 195 } 196 197 for (auto VT : 198 { MVT::nxv2i8, MVT::nxv2i16, MVT::nxv2i32, MVT::nxv2i64, MVT::nxv4i8, 199 MVT::nxv4i16, MVT::nxv4i32, MVT::nxv8i8, MVT::nxv8i16 }) 200 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Legal); 201 } 202 203 // Compute derived properties from the register classes 204 computeRegisterProperties(Subtarget->getRegisterInfo()); 205 206 // Provide all sorts of operation actions 207 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 208 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 209 setOperationAction(ISD::SETCC, MVT::i32, Custom); 210 setOperationAction(ISD::SETCC, MVT::i64, Custom); 211 setOperationAction(ISD::SETCC, MVT::f16, Custom); 212 setOperationAction(ISD::SETCC, MVT::f32, Custom); 213 setOperationAction(ISD::SETCC, MVT::f64, Custom); 214 setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom); 215 setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom); 216 setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom); 217 setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom); 218 setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom); 219 setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom); 220 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 221 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 222 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 223 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 224 setOperationAction(ISD::BR_CC, MVT::i64, Custom); 225 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 226 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 227 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 228 setOperationAction(ISD::SELECT, MVT::i32, Custom); 229 setOperationAction(ISD::SELECT, MVT::i64, Custom); 230 setOperationAction(ISD::SELECT, MVT::f16, Custom); 231 setOperationAction(ISD::SELECT, MVT::f32, Custom); 232 setOperationAction(ISD::SELECT, MVT::f64, Custom); 233 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 234 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom); 235 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 236 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 237 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 238 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 239 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 240 241 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 242 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 243 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 244 245 setOperationAction(ISD::FREM, MVT::f32, Expand); 246 setOperationAction(ISD::FREM, MVT::f64, Expand); 247 setOperationAction(ISD::FREM, MVT::f80, Expand); 248 249 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 250 251 // Custom lowering hooks are needed for XOR 252 // to fold it into CSINC/CSINV. 253 setOperationAction(ISD::XOR, MVT::i32, Custom); 254 setOperationAction(ISD::XOR, MVT::i64, Custom); 255 256 // Virtually no operation on f128 is legal, but LLVM can't expand them when 257 // there's a valid register class, so we need custom operations in most cases. 258 setOperationAction(ISD::FABS, MVT::f128, Expand); 259 setOperationAction(ISD::FADD, MVT::f128, Custom); 260 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 261 setOperationAction(ISD::FCOS, MVT::f128, Expand); 262 setOperationAction(ISD::FDIV, MVT::f128, Custom); 263 setOperationAction(ISD::FMA, MVT::f128, Expand); 264 setOperationAction(ISD::FMUL, MVT::f128, Custom); 265 setOperationAction(ISD::FNEG, MVT::f128, Expand); 266 setOperationAction(ISD::FPOW, MVT::f128, Expand); 267 setOperationAction(ISD::FREM, MVT::f128, Expand); 268 setOperationAction(ISD::FRINT, MVT::f128, Expand); 269 setOperationAction(ISD::FSIN, MVT::f128, Expand); 270 setOperationAction(ISD::FSINCOS, MVT::f128, Expand); 271 setOperationAction(ISD::FSQRT, MVT::f128, Expand); 272 setOperationAction(ISD::FSUB, MVT::f128, Custom); 273 setOperationAction(ISD::FTRUNC, MVT::f128, Expand); 274 setOperationAction(ISD::SETCC, MVT::f128, Custom); 275 setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom); 276 setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom); 277 setOperationAction(ISD::BR_CC, MVT::f128, Custom); 278 setOperationAction(ISD::SELECT, MVT::f128, Custom); 279 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); 280 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom); 281 282 // Lowering for many of the conversions is actually specified by the non-f128 283 // type. The LowerXXX function will be trivial when f128 isn't involved. 284 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 285 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 286 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom); 287 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom); 288 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom); 289 setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom); 290 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 291 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 292 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom); 293 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom); 294 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom); 295 setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom); 296 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 297 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 298 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom); 299 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom); 300 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom); 301 setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom); 302 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 303 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 304 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom); 305 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom); 306 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom); 307 setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom); 308 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 309 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom); 310 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom); 311 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom); 312 313 // Variable arguments. 314 setOperationAction(ISD::VASTART, MVT::Other, Custom); 315 setOperationAction(ISD::VAARG, MVT::Other, Custom); 316 setOperationAction(ISD::VACOPY, MVT::Other, Custom); 317 setOperationAction(ISD::VAEND, MVT::Other, Expand); 318 319 // Variable-sized objects. 320 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 321 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 322 323 if (Subtarget->isTargetWindows()) 324 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom); 325 else 326 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand); 327 328 // Constant pool entries 329 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 330 331 // BlockAddress 332 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 333 334 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences. 335 setOperationAction(ISD::ADDC, MVT::i32, Custom); 336 setOperationAction(ISD::ADDE, MVT::i32, Custom); 337 setOperationAction(ISD::SUBC, MVT::i32, Custom); 338 setOperationAction(ISD::SUBE, MVT::i32, Custom); 339 setOperationAction(ISD::ADDC, MVT::i64, Custom); 340 setOperationAction(ISD::ADDE, MVT::i64, Custom); 341 setOperationAction(ISD::SUBC, MVT::i64, Custom); 342 setOperationAction(ISD::SUBE, MVT::i64, Custom); 343 344 // AArch64 lacks both left-rotate and popcount instructions. 345 setOperationAction(ISD::ROTL, MVT::i32, Expand); 346 setOperationAction(ISD::ROTL, MVT::i64, Expand); 347 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 348 setOperationAction(ISD::ROTL, VT, Expand); 349 setOperationAction(ISD::ROTR, VT, Expand); 350 } 351 352 // AArch64 doesn't have {U|S}MUL_LOHI. 353 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 354 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 355 356 setOperationAction(ISD::CTPOP, MVT::i32, Custom); 357 setOperationAction(ISD::CTPOP, MVT::i64, Custom); 358 359 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 360 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 361 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 362 setOperationAction(ISD::SDIVREM, VT, Expand); 363 setOperationAction(ISD::UDIVREM, VT, Expand); 364 } 365 setOperationAction(ISD::SREM, MVT::i32, Expand); 366 setOperationAction(ISD::SREM, MVT::i64, Expand); 367 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 368 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 369 setOperationAction(ISD::UREM, MVT::i32, Expand); 370 setOperationAction(ISD::UREM, MVT::i64, Expand); 371 372 // Custom lower Add/Sub/Mul with overflow. 373 setOperationAction(ISD::SADDO, MVT::i32, Custom); 374 setOperationAction(ISD::SADDO, MVT::i64, Custom); 375 setOperationAction(ISD::UADDO, MVT::i32, Custom); 376 setOperationAction(ISD::UADDO, MVT::i64, Custom); 377 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 378 setOperationAction(ISD::SSUBO, MVT::i64, Custom); 379 setOperationAction(ISD::USUBO, MVT::i32, Custom); 380 setOperationAction(ISD::USUBO, MVT::i64, Custom); 381 setOperationAction(ISD::SMULO, MVT::i32, Custom); 382 setOperationAction(ISD::SMULO, MVT::i64, Custom); 383 setOperationAction(ISD::UMULO, MVT::i32, Custom); 384 setOperationAction(ISD::UMULO, MVT::i64, Custom); 385 386 setOperationAction(ISD::FSIN, MVT::f32, Expand); 387 setOperationAction(ISD::FSIN, MVT::f64, Expand); 388 setOperationAction(ISD::FCOS, MVT::f32, Expand); 389 setOperationAction(ISD::FCOS, MVT::f64, Expand); 390 setOperationAction(ISD::FPOW, MVT::f32, Expand); 391 setOperationAction(ISD::FPOW, MVT::f64, Expand); 392 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 393 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 394 if (Subtarget->hasFullFP16()) 395 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom); 396 else 397 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote); 398 399 setOperationAction(ISD::FREM, MVT::f16, Promote); 400 setOperationAction(ISD::FREM, MVT::v4f16, Expand); 401 setOperationAction(ISD::FREM, MVT::v8f16, Expand); 402 setOperationAction(ISD::FPOW, MVT::f16, Promote); 403 setOperationAction(ISD::FPOW, MVT::v4f16, Expand); 404 setOperationAction(ISD::FPOW, MVT::v8f16, Expand); 405 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 406 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand); 407 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand); 408 setOperationAction(ISD::FCOS, MVT::f16, Promote); 409 setOperationAction(ISD::FCOS, MVT::v4f16, Expand); 410 setOperationAction(ISD::FCOS, MVT::v8f16, Expand); 411 setOperationAction(ISD::FSIN, MVT::f16, Promote); 412 setOperationAction(ISD::FSIN, MVT::v4f16, Expand); 413 setOperationAction(ISD::FSIN, MVT::v8f16, Expand); 414 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 415 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand); 416 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand); 417 setOperationAction(ISD::FEXP, MVT::f16, Promote); 418 setOperationAction(ISD::FEXP, MVT::v4f16, Expand); 419 setOperationAction(ISD::FEXP, MVT::v8f16, Expand); 420 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 421 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand); 422 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand); 423 setOperationAction(ISD::FLOG, MVT::f16, Promote); 424 setOperationAction(ISD::FLOG, MVT::v4f16, Expand); 425 setOperationAction(ISD::FLOG, MVT::v8f16, Expand); 426 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 427 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand); 428 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand); 429 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 430 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand); 431 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand); 432 433 if (!Subtarget->hasFullFP16()) { 434 setOperationAction(ISD::SELECT, MVT::f16, Promote); 435 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote); 436 setOperationAction(ISD::SETCC, MVT::f16, Promote); 437 setOperationAction(ISD::BR_CC, MVT::f16, Promote); 438 setOperationAction(ISD::FADD, MVT::f16, Promote); 439 setOperationAction(ISD::FSUB, MVT::f16, Promote); 440 setOperationAction(ISD::FMUL, MVT::f16, Promote); 441 setOperationAction(ISD::FDIV, MVT::f16, Promote); 442 setOperationAction(ISD::FMA, MVT::f16, Promote); 443 setOperationAction(ISD::FNEG, MVT::f16, Promote); 444 setOperationAction(ISD::FABS, MVT::f16, Promote); 445 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 446 setOperationAction(ISD::FSQRT, MVT::f16, Promote); 447 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 448 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 449 setOperationAction(ISD::FRINT, MVT::f16, Promote); 450 setOperationAction(ISD::FROUND, MVT::f16, Promote); 451 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 452 setOperationAction(ISD::FMINNUM, MVT::f16, Promote); 453 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote); 454 setOperationAction(ISD::FMINIMUM, MVT::f16, Promote); 455 setOperationAction(ISD::FMAXIMUM, MVT::f16, Promote); 456 457 // promote v4f16 to v4f32 when that is known to be safe. 458 setOperationAction(ISD::FADD, MVT::v4f16, Promote); 459 setOperationAction(ISD::FSUB, MVT::v4f16, Promote); 460 setOperationAction(ISD::FMUL, MVT::v4f16, Promote); 461 setOperationAction(ISD::FDIV, MVT::v4f16, Promote); 462 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32); 463 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32); 464 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32); 465 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32); 466 467 setOperationAction(ISD::FABS, MVT::v4f16, Expand); 468 setOperationAction(ISD::FNEG, MVT::v4f16, Expand); 469 setOperationAction(ISD::FROUND, MVT::v4f16, Expand); 470 setOperationAction(ISD::FMA, MVT::v4f16, Expand); 471 setOperationAction(ISD::SETCC, MVT::v4f16, Expand); 472 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand); 473 setOperationAction(ISD::SELECT, MVT::v4f16, Expand); 474 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand); 475 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand); 476 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand); 477 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand); 478 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand); 479 setOperationAction(ISD::FRINT, MVT::v4f16, Expand); 480 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand); 481 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand); 482 483 setOperationAction(ISD::FABS, MVT::v8f16, Expand); 484 setOperationAction(ISD::FADD, MVT::v8f16, Expand); 485 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand); 486 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand); 487 setOperationAction(ISD::FDIV, MVT::v8f16, Expand); 488 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand); 489 setOperationAction(ISD::FMA, MVT::v8f16, Expand); 490 setOperationAction(ISD::FMUL, MVT::v8f16, Expand); 491 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand); 492 setOperationAction(ISD::FNEG, MVT::v8f16, Expand); 493 setOperationAction(ISD::FROUND, MVT::v8f16, Expand); 494 setOperationAction(ISD::FRINT, MVT::v8f16, Expand); 495 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand); 496 setOperationAction(ISD::FSUB, MVT::v8f16, Expand); 497 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand); 498 setOperationAction(ISD::SETCC, MVT::v8f16, Expand); 499 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand); 500 setOperationAction(ISD::SELECT, MVT::v8f16, Expand); 501 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand); 502 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand); 503 } 504 505 // AArch64 has implementations of a lot of rounding-like FP operations. 506 for (MVT Ty : {MVT::f32, MVT::f64}) { 507 setOperationAction(ISD::FFLOOR, Ty, Legal); 508 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 509 setOperationAction(ISD::FCEIL, Ty, Legal); 510 setOperationAction(ISD::FRINT, Ty, Legal); 511 setOperationAction(ISD::FTRUNC, Ty, Legal); 512 setOperationAction(ISD::FROUND, Ty, Legal); 513 setOperationAction(ISD::FMINNUM, Ty, Legal); 514 setOperationAction(ISD::FMAXNUM, Ty, Legal); 515 setOperationAction(ISD::FMINIMUM, Ty, Legal); 516 setOperationAction(ISD::FMAXIMUM, Ty, Legal); 517 setOperationAction(ISD::LROUND, Ty, Legal); 518 setOperationAction(ISD::LLROUND, Ty, Legal); 519 setOperationAction(ISD::LRINT, Ty, Legal); 520 setOperationAction(ISD::LLRINT, Ty, Legal); 521 } 522 523 if (Subtarget->hasFullFP16()) { 524 setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal); 525 setOperationAction(ISD::FFLOOR, MVT::f16, Legal); 526 setOperationAction(ISD::FCEIL, MVT::f16, Legal); 527 setOperationAction(ISD::FRINT, MVT::f16, Legal); 528 setOperationAction(ISD::FTRUNC, MVT::f16, Legal); 529 setOperationAction(ISD::FROUND, MVT::f16, Legal); 530 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 531 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 532 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal); 533 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal); 534 } 535 536 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 537 538 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 539 540 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom); 541 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom); 542 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom); 543 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom); 544 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom); 545 546 // 128-bit loads and stores can be done without expanding 547 setOperationAction(ISD::LOAD, MVT::i128, Custom); 548 setOperationAction(ISD::STORE, MVT::i128, Custom); 549 550 // 256 bit non-temporal stores can be lowered to STNP. Do this as part of the 551 // custom lowering, as there are no un-paired non-temporal stores and 552 // legalization will break up 256 bit inputs. 553 setOperationAction(ISD::STORE, MVT::v32i8, Custom); 554 setOperationAction(ISD::STORE, MVT::v16i16, Custom); 555 setOperationAction(ISD::STORE, MVT::v16f16, Custom); 556 setOperationAction(ISD::STORE, MVT::v8i32, Custom); 557 setOperationAction(ISD::STORE, MVT::v8f32, Custom); 558 setOperationAction(ISD::STORE, MVT::v4f64, Custom); 559 setOperationAction(ISD::STORE, MVT::v4i64, Custom); 560 561 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0. 562 // This requires the Performance Monitors extension. 563 if (Subtarget->hasPerfMon()) 564 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 565 566 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 567 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 568 // Issue __sincos_stret if available. 569 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 570 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 571 } else { 572 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 573 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 574 } 575 576 if (Subtarget->getTargetTriple().isOSMSVCRT()) { 577 // MSVCRT doesn't have powi; fall back to pow 578 setLibcallName(RTLIB::POWI_F32, nullptr); 579 setLibcallName(RTLIB::POWI_F64, nullptr); 580 } 581 582 // Make floating-point constants legal for the large code model, so they don't 583 // become loads from the constant pool. 584 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) { 585 setOperationAction(ISD::ConstantFP, MVT::f32, Legal); 586 setOperationAction(ISD::ConstantFP, MVT::f64, Legal); 587 } 588 589 // AArch64 does not have floating-point extending loads, i1 sign-extending 590 // load, floating-point truncating stores, or v2i32->v2i16 truncating store. 591 for (MVT VT : MVT::fp_valuetypes()) { 592 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 593 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 594 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand); 595 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand); 596 } 597 for (MVT VT : MVT::integer_valuetypes()) 598 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand); 599 600 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 601 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 602 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 603 setTruncStoreAction(MVT::f128, MVT::f80, Expand); 604 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 605 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 606 setTruncStoreAction(MVT::f128, MVT::f16, Expand); 607 608 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 609 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 610 611 // Indexed loads and stores are supported. 612 for (unsigned im = (unsigned)ISD::PRE_INC; 613 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 614 setIndexedLoadAction(im, MVT::i8, Legal); 615 setIndexedLoadAction(im, MVT::i16, Legal); 616 setIndexedLoadAction(im, MVT::i32, Legal); 617 setIndexedLoadAction(im, MVT::i64, Legal); 618 setIndexedLoadAction(im, MVT::f64, Legal); 619 setIndexedLoadAction(im, MVT::f32, Legal); 620 setIndexedLoadAction(im, MVT::f16, Legal); 621 setIndexedStoreAction(im, MVT::i8, Legal); 622 setIndexedStoreAction(im, MVT::i16, Legal); 623 setIndexedStoreAction(im, MVT::i32, Legal); 624 setIndexedStoreAction(im, MVT::i64, Legal); 625 setIndexedStoreAction(im, MVT::f64, Legal); 626 setIndexedStoreAction(im, MVT::f32, Legal); 627 setIndexedStoreAction(im, MVT::f16, Legal); 628 } 629 630 // Trap. 631 setOperationAction(ISD::TRAP, MVT::Other, Legal); 632 if (Subtarget->isTargetWindows()) 633 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 634 635 // We combine OR nodes for bitfield operations. 636 setTargetDAGCombine(ISD::OR); 637 // Try to create BICs for vector ANDs. 638 setTargetDAGCombine(ISD::AND); 639 640 // Vector add and sub nodes may conceal a high-half opportunity. 641 // Also, try to fold ADD into CSINC/CSINV.. 642 setTargetDAGCombine(ISD::ADD); 643 setTargetDAGCombine(ISD::SUB); 644 setTargetDAGCombine(ISD::SRL); 645 setTargetDAGCombine(ISD::XOR); 646 setTargetDAGCombine(ISD::SINT_TO_FP); 647 setTargetDAGCombine(ISD::UINT_TO_FP); 648 649 setTargetDAGCombine(ISD::FP_TO_SINT); 650 setTargetDAGCombine(ISD::FP_TO_UINT); 651 setTargetDAGCombine(ISD::FDIV); 652 653 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 654 655 setTargetDAGCombine(ISD::ANY_EXTEND); 656 setTargetDAGCombine(ISD::ZERO_EXTEND); 657 setTargetDAGCombine(ISD::SIGN_EXTEND); 658 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 659 setTargetDAGCombine(ISD::CONCAT_VECTORS); 660 setTargetDAGCombine(ISD::STORE); 661 if (Subtarget->supportsAddressTopByteIgnored()) 662 setTargetDAGCombine(ISD::LOAD); 663 664 setTargetDAGCombine(ISD::MUL); 665 666 setTargetDAGCombine(ISD::SELECT); 667 setTargetDAGCombine(ISD::VSELECT); 668 669 setTargetDAGCombine(ISD::INTRINSIC_VOID); 670 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 671 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 672 673 setTargetDAGCombine(ISD::GlobalAddress); 674 675 // In case of strict alignment, avoid an excessive number of byte wide stores. 676 MaxStoresPerMemsetOptSize = 8; 677 MaxStoresPerMemset = Subtarget->requiresStrictAlign() 678 ? MaxStoresPerMemsetOptSize : 32; 679 680 MaxGluedStoresPerMemcpy = 4; 681 MaxStoresPerMemcpyOptSize = 4; 682 MaxStoresPerMemcpy = Subtarget->requiresStrictAlign() 683 ? MaxStoresPerMemcpyOptSize : 16; 684 685 MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4; 686 687 MaxLoadsPerMemcmpOptSize = 4; 688 MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign() 689 ? MaxLoadsPerMemcmpOptSize : 8; 690 691 setStackPointerRegisterToSaveRestore(AArch64::SP); 692 693 setSchedulingPreference(Sched::Hybrid); 694 695 EnableExtLdPromotion = true; 696 697 // Set required alignment. 698 setMinFunctionAlignment(Align(4)); 699 // Set preferred alignments. 700 setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment())); 701 setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment())); 702 703 // Only change the limit for entries in a jump table if specified by 704 // the sub target, but not at the command line. 705 unsigned MaxJT = STI.getMaximumJumpTableSize(); 706 if (MaxJT && getMaximumJumpTableSize() == UINT_MAX) 707 setMaximumJumpTableSize(MaxJT); 708 709 setHasExtractBitsInsn(true); 710 711 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 712 713 if (Subtarget->hasNEON()) { 714 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to 715 // silliness like this: 716 setOperationAction(ISD::FABS, MVT::v1f64, Expand); 717 setOperationAction(ISD::FADD, MVT::v1f64, Expand); 718 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand); 719 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand); 720 setOperationAction(ISD::FCOS, MVT::v1f64, Expand); 721 setOperationAction(ISD::FDIV, MVT::v1f64, Expand); 722 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand); 723 setOperationAction(ISD::FMA, MVT::v1f64, Expand); 724 setOperationAction(ISD::FMUL, MVT::v1f64, Expand); 725 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand); 726 setOperationAction(ISD::FNEG, MVT::v1f64, Expand); 727 setOperationAction(ISD::FPOW, MVT::v1f64, Expand); 728 setOperationAction(ISD::FREM, MVT::v1f64, Expand); 729 setOperationAction(ISD::FROUND, MVT::v1f64, Expand); 730 setOperationAction(ISD::FRINT, MVT::v1f64, Expand); 731 setOperationAction(ISD::FSIN, MVT::v1f64, Expand); 732 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand); 733 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand); 734 setOperationAction(ISD::FSUB, MVT::v1f64, Expand); 735 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand); 736 setOperationAction(ISD::SETCC, MVT::v1f64, Expand); 737 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand); 738 setOperationAction(ISD::SELECT, MVT::v1f64, Expand); 739 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand); 740 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand); 741 742 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand); 743 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand); 744 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand); 745 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand); 746 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand); 747 748 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 749 750 // AArch64 doesn't have a direct vector ->f32 conversion instructions for 751 // elements smaller than i32, so promote the input to i32 first. 752 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32); 753 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32); 754 // i8 vector elements also need promotion to i32 for v8i8 755 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32); 756 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32); 757 // Similarly, there is no direct i32 -> f64 vector conversion instruction. 758 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom); 759 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom); 760 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom); 761 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom); 762 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the 763 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16 764 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom); 765 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom); 766 767 if (Subtarget->hasFullFP16()) { 768 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 769 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 770 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom); 771 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); 772 } else { 773 // when AArch64 doesn't have fullfp16 support, promote the input 774 // to i32 first. 775 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32); 776 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32); 777 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32); 778 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32); 779 } 780 781 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 782 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 783 784 // AArch64 doesn't have MUL.2d: 785 setOperationAction(ISD::MUL, MVT::v2i64, Expand); 786 // Custom handling for some quad-vector types to detect MULL. 787 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 788 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 789 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 790 791 for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32, 792 MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) { 793 // Vector reductions 794 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 795 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 796 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 797 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 798 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 799 800 // Saturates 801 setOperationAction(ISD::SADDSAT, VT, Legal); 802 setOperationAction(ISD::UADDSAT, VT, Legal); 803 setOperationAction(ISD::SSUBSAT, VT, Legal); 804 setOperationAction(ISD::USUBSAT, VT, Legal); 805 } 806 for (MVT VT : { MVT::v4f16, MVT::v2f32, 807 MVT::v8f16, MVT::v4f32, MVT::v2f64 }) { 808 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 809 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 810 } 811 812 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal); 813 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 814 // Likewise, narrowing and extending vector loads/stores aren't handled 815 // directly. 816 for (MVT VT : MVT::fixedlen_vector_valuetypes()) { 817 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 818 819 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) { 820 setOperationAction(ISD::MULHS, VT, Legal); 821 setOperationAction(ISD::MULHU, VT, Legal); 822 } else { 823 setOperationAction(ISD::MULHS, VT, Expand); 824 setOperationAction(ISD::MULHU, VT, Expand); 825 } 826 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 827 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 828 829 setOperationAction(ISD::BSWAP, VT, Expand); 830 setOperationAction(ISD::CTTZ, VT, Expand); 831 832 for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) { 833 setTruncStoreAction(VT, InnerVT, Expand); 834 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 835 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 836 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 837 } 838 } 839 840 // AArch64 has implementations of a lot of rounding-like FP operations. 841 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) { 842 setOperationAction(ISD::FFLOOR, Ty, Legal); 843 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 844 setOperationAction(ISD::FCEIL, Ty, Legal); 845 setOperationAction(ISD::FRINT, Ty, Legal); 846 setOperationAction(ISD::FTRUNC, Ty, Legal); 847 setOperationAction(ISD::FROUND, Ty, Legal); 848 } 849 850 if (Subtarget->hasFullFP16()) { 851 for (MVT Ty : {MVT::v4f16, MVT::v8f16}) { 852 setOperationAction(ISD::FFLOOR, Ty, Legal); 853 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 854 setOperationAction(ISD::FCEIL, Ty, Legal); 855 setOperationAction(ISD::FRINT, Ty, Legal); 856 setOperationAction(ISD::FTRUNC, Ty, Legal); 857 setOperationAction(ISD::FROUND, Ty, Legal); 858 } 859 } 860 861 if (Subtarget->hasSVE()) 862 setOperationAction(ISD::VSCALE, MVT::i32, Custom); 863 864 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom); 865 } 866 867 if (Subtarget->hasSVE()) { 868 // FIXME: Add custom lowering of MLOAD to handle different passthrus (not a 869 // splat of 0 or undef) once vector selects supported in SVE codegen. See 870 // D68877 for more details. 871 for (MVT VT : MVT::integer_scalable_vector_valuetypes()) { 872 if (isTypeLegal(VT)) 873 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 874 } 875 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom); 876 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom); 877 878 for (MVT VT : MVT::fp_scalable_vector_valuetypes()) { 879 if (isTypeLegal(VT)) { 880 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 881 } 882 } 883 } 884 885 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive(); 886 } 887 888 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) { 889 assert(VT.isVector() && "VT should be a vector type"); 890 891 if (VT.isFloatingPoint()) { 892 MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT(); 893 setOperationPromotedToType(ISD::LOAD, VT, PromoteTo); 894 setOperationPromotedToType(ISD::STORE, VT, PromoteTo); 895 } 896 897 // Mark vector float intrinsics as expand. 898 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) { 899 setOperationAction(ISD::FSIN, VT, Expand); 900 setOperationAction(ISD::FCOS, VT, Expand); 901 setOperationAction(ISD::FPOW, VT, Expand); 902 setOperationAction(ISD::FLOG, VT, Expand); 903 setOperationAction(ISD::FLOG2, VT, Expand); 904 setOperationAction(ISD::FLOG10, VT, Expand); 905 setOperationAction(ISD::FEXP, VT, Expand); 906 setOperationAction(ISD::FEXP2, VT, Expand); 907 908 // But we do support custom-lowering for FCOPYSIGN. 909 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 910 } 911 912 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 913 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 914 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 915 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 916 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 917 setOperationAction(ISD::SRA, VT, Custom); 918 setOperationAction(ISD::SRL, VT, Custom); 919 setOperationAction(ISD::SHL, VT, Custom); 920 setOperationAction(ISD::OR, VT, Custom); 921 setOperationAction(ISD::SETCC, VT, Custom); 922 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 923 924 setOperationAction(ISD::SELECT, VT, Expand); 925 setOperationAction(ISD::SELECT_CC, VT, Expand); 926 setOperationAction(ISD::VSELECT, VT, Expand); 927 for (MVT InnerVT : MVT::all_valuetypes()) 928 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand); 929 930 // CNT supports only B element sizes, then use UADDLP to widen. 931 if (VT != MVT::v8i8 && VT != MVT::v16i8) 932 setOperationAction(ISD::CTPOP, VT, Custom); 933 934 setOperationAction(ISD::UDIV, VT, Expand); 935 setOperationAction(ISD::SDIV, VT, Expand); 936 setOperationAction(ISD::UREM, VT, Expand); 937 setOperationAction(ISD::SREM, VT, Expand); 938 setOperationAction(ISD::FREM, VT, Expand); 939 940 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 941 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 942 943 if (!VT.isFloatingPoint()) 944 setOperationAction(ISD::ABS, VT, Legal); 945 946 // [SU][MIN|MAX] are available for all NEON types apart from i64. 947 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64) 948 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 949 setOperationAction(Opcode, VT, Legal); 950 951 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types. 952 if (VT.isFloatingPoint() && 953 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16())) 954 for (unsigned Opcode : 955 {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM}) 956 setOperationAction(Opcode, VT, Legal); 957 958 if (Subtarget->isLittleEndian()) { 959 for (unsigned im = (unsigned)ISD::PRE_INC; 960 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 961 setIndexedLoadAction(im, VT, Legal); 962 setIndexedStoreAction(im, VT, Legal); 963 } 964 } 965 } 966 967 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) { 968 addRegisterClass(VT, &AArch64::FPR64RegClass); 969 addTypeForNEON(VT, MVT::v2i32); 970 } 971 972 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) { 973 addRegisterClass(VT, &AArch64::FPR128RegClass); 974 addTypeForNEON(VT, MVT::v4i32); 975 } 976 977 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &, 978 EVT VT) const { 979 if (!VT.isVector()) 980 return MVT::i32; 981 return VT.changeVectorElementTypeToInteger(); 982 } 983 984 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm, 985 const APInt &Demanded, 986 TargetLowering::TargetLoweringOpt &TLO, 987 unsigned NewOpc) { 988 uint64_t OldImm = Imm, NewImm, Enc; 989 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask; 990 991 // Return if the immediate is already all zeros, all ones, a bimm32 or a 992 // bimm64. 993 if (Imm == 0 || Imm == Mask || 994 AArch64_AM::isLogicalImmediate(Imm & Mask, Size)) 995 return false; 996 997 unsigned EltSize = Size; 998 uint64_t DemandedBits = Demanded.getZExtValue(); 999 1000 // Clear bits that are not demanded. 1001 Imm &= DemandedBits; 1002 1003 while (true) { 1004 // The goal here is to set the non-demanded bits in a way that minimizes 1005 // the number of switching between 0 and 1. In order to achieve this goal, 1006 // we set the non-demanded bits to the value of the preceding demanded bits. 1007 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a 1008 // non-demanded bit), we copy bit0 (1) to the least significant 'x', 1009 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'. 1010 // The final result is 0b11000011. 1011 uint64_t NonDemandedBits = ~DemandedBits; 1012 uint64_t InvertedImm = ~Imm & DemandedBits; 1013 uint64_t RotatedImm = 1014 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) & 1015 NonDemandedBits; 1016 uint64_t Sum = RotatedImm + NonDemandedBits; 1017 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1)); 1018 uint64_t Ones = (Sum + Carry) & NonDemandedBits; 1019 NewImm = (Imm | Ones) & Mask; 1020 1021 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate 1022 // or all-ones or all-zeros, in which case we can stop searching. Otherwise, 1023 // we halve the element size and continue the search. 1024 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask))) 1025 break; 1026 1027 // We cannot shrink the element size any further if it is 2-bits. 1028 if (EltSize == 2) 1029 return false; 1030 1031 EltSize /= 2; 1032 Mask >>= EltSize; 1033 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize; 1034 1035 // Return if there is mismatch in any of the demanded bits of Imm and Hi. 1036 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0) 1037 return false; 1038 1039 // Merge the upper and lower halves of Imm and DemandedBits. 1040 Imm |= Hi; 1041 DemandedBits |= DemandedBitsHi; 1042 } 1043 1044 ++NumOptimizedImms; 1045 1046 // Replicate the element across the register width. 1047 while (EltSize < Size) { 1048 NewImm |= NewImm << EltSize; 1049 EltSize *= 2; 1050 } 1051 1052 (void)OldImm; 1053 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 && 1054 "demanded bits should never be altered"); 1055 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm"); 1056 1057 // Create the new constant immediate node. 1058 EVT VT = Op.getValueType(); 1059 SDLoc DL(Op); 1060 SDValue New; 1061 1062 // If the new constant immediate is all-zeros or all-ones, let the target 1063 // independent DAG combine optimize this node. 1064 if (NewImm == 0 || NewImm == OrigMask) { 1065 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0), 1066 TLO.DAG.getConstant(NewImm, DL, VT)); 1067 // Otherwise, create a machine node so that target independent DAG combine 1068 // doesn't undo this optimization. 1069 } else { 1070 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size); 1071 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT); 1072 New = SDValue( 1073 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0); 1074 } 1075 1076 return TLO.CombineTo(Op, New); 1077 } 1078 1079 bool AArch64TargetLowering::targetShrinkDemandedConstant( 1080 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const { 1081 // Delay this optimization to as late as possible. 1082 if (!TLO.LegalOps) 1083 return false; 1084 1085 if (!EnableOptimizeLogicalImm) 1086 return false; 1087 1088 EVT VT = Op.getValueType(); 1089 if (VT.isVector()) 1090 return false; 1091 1092 unsigned Size = VT.getSizeInBits(); 1093 assert((Size == 32 || Size == 64) && 1094 "i32 or i64 is expected after legalization."); 1095 1096 // Exit early if we demand all bits. 1097 if (Demanded.countPopulation() == Size) 1098 return false; 1099 1100 unsigned NewOpc; 1101 switch (Op.getOpcode()) { 1102 default: 1103 return false; 1104 case ISD::AND: 1105 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri; 1106 break; 1107 case ISD::OR: 1108 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri; 1109 break; 1110 case ISD::XOR: 1111 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri; 1112 break; 1113 } 1114 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 1115 if (!C) 1116 return false; 1117 uint64_t Imm = C->getZExtValue(); 1118 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc); 1119 } 1120 1121 /// computeKnownBitsForTargetNode - Determine which of the bits specified in 1122 /// Mask are known to be either zero or one and return them Known. 1123 void AArch64TargetLowering::computeKnownBitsForTargetNode( 1124 const SDValue Op, KnownBits &Known, 1125 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const { 1126 switch (Op.getOpcode()) { 1127 default: 1128 break; 1129 case AArch64ISD::CSEL: { 1130 KnownBits Known2; 1131 Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1); 1132 Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1); 1133 Known.Zero &= Known2.Zero; 1134 Known.One &= Known2.One; 1135 break; 1136 } 1137 case AArch64ISD::LOADgot: 1138 case AArch64ISD::ADDlow: { 1139 if (!Subtarget->isTargetILP32()) 1140 break; 1141 // In ILP32 mode all valid pointers are in the low 4GB of the address-space. 1142 Known.Zero = APInt::getHighBitsSet(64, 32); 1143 break; 1144 } 1145 case ISD::INTRINSIC_W_CHAIN: { 1146 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 1147 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 1148 switch (IntID) { 1149 default: return; 1150 case Intrinsic::aarch64_ldaxr: 1151 case Intrinsic::aarch64_ldxr: { 1152 unsigned BitWidth = Known.getBitWidth(); 1153 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 1154 unsigned MemBits = VT.getScalarSizeInBits(); 1155 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 1156 return; 1157 } 1158 } 1159 break; 1160 } 1161 case ISD::INTRINSIC_WO_CHAIN: 1162 case ISD::INTRINSIC_VOID: { 1163 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 1164 switch (IntNo) { 1165 default: 1166 break; 1167 case Intrinsic::aarch64_neon_umaxv: 1168 case Intrinsic::aarch64_neon_uminv: { 1169 // Figure out the datatype of the vector operand. The UMINV instruction 1170 // will zero extend the result, so we can mark as known zero all the 1171 // bits larger than the element datatype. 32-bit or larget doesn't need 1172 // this as those are legal types and will be handled by isel directly. 1173 MVT VT = Op.getOperand(1).getValueType().getSimpleVT(); 1174 unsigned BitWidth = Known.getBitWidth(); 1175 if (VT == MVT::v8i8 || VT == MVT::v16i8) { 1176 assert(BitWidth >= 8 && "Unexpected width!"); 1177 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8); 1178 Known.Zero |= Mask; 1179 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) { 1180 assert(BitWidth >= 16 && "Unexpected width!"); 1181 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16); 1182 Known.Zero |= Mask; 1183 } 1184 break; 1185 } break; 1186 } 1187 } 1188 } 1189 } 1190 1191 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL, 1192 EVT) const { 1193 return MVT::i64; 1194 } 1195 1196 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses( 1197 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1198 bool *Fast) const { 1199 if (Subtarget->requiresStrictAlign()) 1200 return false; 1201 1202 if (Fast) { 1203 // Some CPUs are fine with unaligned stores except for 128-bit ones. 1204 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 || 1205 // See comments in performSTORECombine() for more details about 1206 // these conditions. 1207 1208 // Code that uses clang vector extensions can mark that it 1209 // wants unaligned accesses to be treated as fast by 1210 // underspecifying alignment to be 1 or 2. 1211 Align <= 2 || 1212 1213 // Disregard v2i64. Memcpy lowering produces those and splitting 1214 // them regresses performance on micro-benchmarks and olden/bh. 1215 VT == MVT::v2i64; 1216 } 1217 return true; 1218 } 1219 1220 // Same as above but handling LLTs instead. 1221 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses( 1222 LLT Ty, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1223 bool *Fast) const { 1224 if (Subtarget->requiresStrictAlign()) 1225 return false; 1226 1227 if (Fast) { 1228 // Some CPUs are fine with unaligned stores except for 128-bit ones. 1229 *Fast = !Subtarget->isMisaligned128StoreSlow() || 1230 Ty.getSizeInBytes() != 16 || 1231 // See comments in performSTORECombine() for more details about 1232 // these conditions. 1233 1234 // Code that uses clang vector extensions can mark that it 1235 // wants unaligned accesses to be treated as fast by 1236 // underspecifying alignment to be 1 or 2. 1237 Align <= 2 || 1238 1239 // Disregard v2i64. Memcpy lowering produces those and splitting 1240 // them regresses performance on micro-benchmarks and olden/bh. 1241 Ty == LLT::vector(2, 64); 1242 } 1243 return true; 1244 } 1245 1246 FastISel * 1247 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1248 const TargetLibraryInfo *libInfo) const { 1249 return AArch64::createFastISel(funcInfo, libInfo); 1250 } 1251 1252 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const { 1253 switch ((AArch64ISD::NodeType)Opcode) { 1254 case AArch64ISD::FIRST_NUMBER: break; 1255 case AArch64ISD::CALL: return "AArch64ISD::CALL"; 1256 case AArch64ISD::ADRP: return "AArch64ISD::ADRP"; 1257 case AArch64ISD::ADR: return "AArch64ISD::ADR"; 1258 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow"; 1259 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot"; 1260 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG"; 1261 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND"; 1262 case AArch64ISD::CSEL: return "AArch64ISD::CSEL"; 1263 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL"; 1264 case AArch64ISD::CSINV: return "AArch64ISD::CSINV"; 1265 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG"; 1266 case AArch64ISD::CSINC: return "AArch64ISD::CSINC"; 1267 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER"; 1268 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ"; 1269 case AArch64ISD::ADC: return "AArch64ISD::ADC"; 1270 case AArch64ISD::SBC: return "AArch64ISD::SBC"; 1271 case AArch64ISD::ADDS: return "AArch64ISD::ADDS"; 1272 case AArch64ISD::SUBS: return "AArch64ISD::SUBS"; 1273 case AArch64ISD::ADCS: return "AArch64ISD::ADCS"; 1274 case AArch64ISD::SBCS: return "AArch64ISD::SBCS"; 1275 case AArch64ISD::ANDS: return "AArch64ISD::ANDS"; 1276 case AArch64ISD::CCMP: return "AArch64ISD::CCMP"; 1277 case AArch64ISD::CCMN: return "AArch64ISD::CCMN"; 1278 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP"; 1279 case AArch64ISD::FCMP: return "AArch64ISD::FCMP"; 1280 case AArch64ISD::STRICT_FCMP: return "AArch64ISD::STRICT_FCMP"; 1281 case AArch64ISD::STRICT_FCMPE: return "AArch64ISD::STRICT_FCMPE"; 1282 case AArch64ISD::DUP: return "AArch64ISD::DUP"; 1283 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8"; 1284 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16"; 1285 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32"; 1286 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64"; 1287 case AArch64ISD::MOVI: return "AArch64ISD::MOVI"; 1288 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift"; 1289 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit"; 1290 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl"; 1291 case AArch64ISD::FMOV: return "AArch64ISD::FMOV"; 1292 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift"; 1293 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl"; 1294 case AArch64ISD::BICi: return "AArch64ISD::BICi"; 1295 case AArch64ISD::ORRi: return "AArch64ISD::ORRi"; 1296 case AArch64ISD::BSP: return "AArch64ISD::BSP"; 1297 case AArch64ISD::NEG: return "AArch64ISD::NEG"; 1298 case AArch64ISD::EXTR: return "AArch64ISD::EXTR"; 1299 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1"; 1300 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2"; 1301 case AArch64ISD::UZP1: return "AArch64ISD::UZP1"; 1302 case AArch64ISD::UZP2: return "AArch64ISD::UZP2"; 1303 case AArch64ISD::TRN1: return "AArch64ISD::TRN1"; 1304 case AArch64ISD::TRN2: return "AArch64ISD::TRN2"; 1305 case AArch64ISD::REV16: return "AArch64ISD::REV16"; 1306 case AArch64ISD::REV32: return "AArch64ISD::REV32"; 1307 case AArch64ISD::REV64: return "AArch64ISD::REV64"; 1308 case AArch64ISD::EXT: return "AArch64ISD::EXT"; 1309 case AArch64ISD::VSHL: return "AArch64ISD::VSHL"; 1310 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR"; 1311 case AArch64ISD::VASHR: return "AArch64ISD::VASHR"; 1312 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ"; 1313 case AArch64ISD::CMGE: return "AArch64ISD::CMGE"; 1314 case AArch64ISD::CMGT: return "AArch64ISD::CMGT"; 1315 case AArch64ISD::CMHI: return "AArch64ISD::CMHI"; 1316 case AArch64ISD::CMHS: return "AArch64ISD::CMHS"; 1317 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ"; 1318 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE"; 1319 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT"; 1320 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz"; 1321 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz"; 1322 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz"; 1323 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz"; 1324 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz"; 1325 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz"; 1326 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz"; 1327 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz"; 1328 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz"; 1329 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz"; 1330 case AArch64ISD::SADDV: return "AArch64ISD::SADDV"; 1331 case AArch64ISD::UADDV: return "AArch64ISD::UADDV"; 1332 case AArch64ISD::SMINV: return "AArch64ISD::SMINV"; 1333 case AArch64ISD::UMINV: return "AArch64ISD::UMINV"; 1334 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV"; 1335 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV"; 1336 case AArch64ISD::SMAXV_PRED: return "AArch64ISD::SMAXV_PRED"; 1337 case AArch64ISD::UMAXV_PRED: return "AArch64ISD::UMAXV_PRED"; 1338 case AArch64ISD::SMINV_PRED: return "AArch64ISD::SMINV_PRED"; 1339 case AArch64ISD::UMINV_PRED: return "AArch64ISD::UMINV_PRED"; 1340 case AArch64ISD::ORV_PRED: return "AArch64ISD::ORV_PRED"; 1341 case AArch64ISD::EORV_PRED: return "AArch64ISD::EORV_PRED"; 1342 case AArch64ISD::ANDV_PRED: return "AArch64ISD::ANDV_PRED"; 1343 case AArch64ISD::CLASTA_N: return "AArch64ISD::CLASTA_N"; 1344 case AArch64ISD::CLASTB_N: return "AArch64ISD::CLASTB_N"; 1345 case AArch64ISD::LASTA: return "AArch64ISD::LASTA"; 1346 case AArch64ISD::LASTB: return "AArch64ISD::LASTB"; 1347 case AArch64ISD::REV: return "AArch64ISD::REV"; 1348 case AArch64ISD::REINTERPRET_CAST: return "AArch64ISD::REINTERPRET_CAST"; 1349 case AArch64ISD::TBL: return "AArch64ISD::TBL"; 1350 case AArch64ISD::NOT: return "AArch64ISD::NOT"; 1351 case AArch64ISD::BIT: return "AArch64ISD::BIT"; 1352 case AArch64ISD::CBZ: return "AArch64ISD::CBZ"; 1353 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ"; 1354 case AArch64ISD::TBZ: return "AArch64ISD::TBZ"; 1355 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ"; 1356 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN"; 1357 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH"; 1358 case AArch64ISD::SITOF: return "AArch64ISD::SITOF"; 1359 case AArch64ISD::UITOF: return "AArch64ISD::UITOF"; 1360 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST"; 1361 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I"; 1362 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I"; 1363 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I"; 1364 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I"; 1365 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I"; 1366 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge"; 1367 case AArch64ISD::LD2post: return "AArch64ISD::LD2post"; 1368 case AArch64ISD::LD3post: return "AArch64ISD::LD3post"; 1369 case AArch64ISD::LD4post: return "AArch64ISD::LD4post"; 1370 case AArch64ISD::ST2post: return "AArch64ISD::ST2post"; 1371 case AArch64ISD::ST3post: return "AArch64ISD::ST3post"; 1372 case AArch64ISD::ST4post: return "AArch64ISD::ST4post"; 1373 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post"; 1374 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post"; 1375 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post"; 1376 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post"; 1377 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post"; 1378 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post"; 1379 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost"; 1380 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost"; 1381 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost"; 1382 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost"; 1383 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost"; 1384 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost"; 1385 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost"; 1386 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost"; 1387 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost"; 1388 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost"; 1389 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost"; 1390 case AArch64ISD::SMULL: return "AArch64ISD::SMULL"; 1391 case AArch64ISD::UMULL: return "AArch64ISD::UMULL"; 1392 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE"; 1393 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS"; 1394 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE"; 1395 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS"; 1396 case AArch64ISD::STG: return "AArch64ISD::STG"; 1397 case AArch64ISD::STZG: return "AArch64ISD::STZG"; 1398 case AArch64ISD::ST2G: return "AArch64ISD::ST2G"; 1399 case AArch64ISD::STZ2G: return "AArch64ISD::STZ2G"; 1400 case AArch64ISD::SUNPKHI: return "AArch64ISD::SUNPKHI"; 1401 case AArch64ISD::SUNPKLO: return "AArch64ISD::SUNPKLO"; 1402 case AArch64ISD::UUNPKHI: return "AArch64ISD::UUNPKHI"; 1403 case AArch64ISD::UUNPKLO: return "AArch64ISD::UUNPKLO"; 1404 case AArch64ISD::INSR: return "AArch64ISD::INSR"; 1405 case AArch64ISD::PTEST: return "AArch64ISD::PTEST"; 1406 case AArch64ISD::PTRUE: return "AArch64ISD::PTRUE"; 1407 case AArch64ISD::LDNF1: return "AArch64ISD::LDNF1"; 1408 case AArch64ISD::LDNF1S: return "AArch64ISD::LDNF1S"; 1409 case AArch64ISD::LDFF1: return "AArch64ISD::LDFF1"; 1410 case AArch64ISD::LDFF1S: return "AArch64ISD::LDFF1S"; 1411 case AArch64ISD::GLD1: return "AArch64ISD::GLD1"; 1412 case AArch64ISD::GLD1_SCALED: return "AArch64ISD::GLD1_SCALED"; 1413 case AArch64ISD::GLD1_SXTW: return "AArch64ISD::GLD1_SXTW"; 1414 case AArch64ISD::GLD1_UXTW: return "AArch64ISD::GLD1_UXTW"; 1415 case AArch64ISD::GLD1_SXTW_SCALED: return "AArch64ISD::GLD1_SXTW_SCALED"; 1416 case AArch64ISD::GLD1_UXTW_SCALED: return "AArch64ISD::GLD1_UXTW_SCALED"; 1417 case AArch64ISD::GLD1_IMM: return "AArch64ISD::GLD1_IMM"; 1418 case AArch64ISD::GLD1S: return "AArch64ISD::GLD1S"; 1419 case AArch64ISD::GLD1S_SCALED: return "AArch64ISD::GLD1S_SCALED"; 1420 case AArch64ISD::GLD1S_SXTW: return "AArch64ISD::GLD1S_SXTW"; 1421 case AArch64ISD::GLD1S_UXTW: return "AArch64ISD::GLD1S_UXTW"; 1422 case AArch64ISD::GLD1S_SXTW_SCALED: return "AArch64ISD::GLD1S_SXTW_SCALED"; 1423 case AArch64ISD::GLD1S_UXTW_SCALED: return "AArch64ISD::GLD1S_UXTW_SCALED"; 1424 case AArch64ISD::GLD1S_IMM: return "AArch64ISD::GLD1S_IMM"; 1425 case AArch64ISD::GLDFF1: return "AArch64ISD::GLDFF1"; 1426 case AArch64ISD::GLDFF1_SCALED: return "AArch64ISD::GLDFF1_SCALED"; 1427 case AArch64ISD::GLDFF1_SXTW: return "AArch64ISD::GLDFF1_SXTW"; 1428 case AArch64ISD::GLDFF1_UXTW: return "AArch64ISD::GLDFF1_UXTW"; 1429 case AArch64ISD::GLDFF1_SXTW_SCALED:return "AArch64ISD::GLDFF1_SXTW_SCALED"; 1430 case AArch64ISD::GLDFF1_UXTW_SCALED:return "AArch64ISD::GLDFF1_UXTW_SCALED"; 1431 case AArch64ISD::GLDFF1_IMM: return "AArch64ISD::GLDFF1_IMM"; 1432 case AArch64ISD::GLDFF1S: return "AArch64ISD::GLDFF1S"; 1433 case AArch64ISD::GLDFF1S_SCALED: return "AArch64ISD::GLDFF1S_SCALED"; 1434 case AArch64ISD::GLDFF1S_SXTW: return "AArch64ISD::GLDFF1S_SXTW"; 1435 case AArch64ISD::GLDFF1S_UXTW: return "AArch64ISD::GLDFF1S_UXTW"; 1436 case AArch64ISD::GLDFF1S_SXTW_SCALED: 1437 return "AArch64ISD::GLDFF1S_SXTW_SCALED"; 1438 case AArch64ISD::GLDFF1S_UXTW_SCALED: 1439 return "AArch64ISD::GLDFF1S_UXTW_SCALED"; 1440 case AArch64ISD::GLDFF1S_IMM: return "AArch64ISD::GLDFF1S_IMM"; 1441 1442 case AArch64ISD::GLDNT1: return "AArch64ISD::GLDNT1"; 1443 case AArch64ISD::GLDNT1_INDEX: return "AArch64ISD::GLDNT1_INDEX"; 1444 case AArch64ISD::GLDNT1S: return "AArch64ISD::GLDNT1S"; 1445 1446 case AArch64ISD::SST1: return "AArch64ISD::SST1"; 1447 case AArch64ISD::SST1_SCALED: return "AArch64ISD::SST1_SCALED"; 1448 case AArch64ISD::SST1_SXTW: return "AArch64ISD::SST1_SXTW"; 1449 case AArch64ISD::SST1_UXTW: return "AArch64ISD::SST1_UXTW"; 1450 case AArch64ISD::SST1_SXTW_SCALED: return "AArch64ISD::SST1_SXTW_SCALED"; 1451 case AArch64ISD::SST1_UXTW_SCALED: return "AArch64ISD::SST1_UXTW_SCALED"; 1452 case AArch64ISD::SST1_IMM: return "AArch64ISD::SST1_IMM"; 1453 1454 case AArch64ISD::SSTNT1: return "AArch64ISD::SSTNT1"; 1455 case AArch64ISD::SSTNT1_INDEX: return "AArch64ISD::SSTNT1_INDEX"; 1456 1457 case AArch64ISD::LDP: return "AArch64ISD::LDP"; 1458 case AArch64ISD::STP: return "AArch64ISD::STP"; 1459 case AArch64ISD::STNP: return "AArch64ISD::STNP"; 1460 case AArch64ISD::DUP_PRED: return "AArch64ISD::DUP_PRED"; 1461 case AArch64ISD::INDEX_VECTOR: return "AArch64ISD::INDEX_VECTOR"; 1462 } 1463 return nullptr; 1464 } 1465 1466 MachineBasicBlock * 1467 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI, 1468 MachineBasicBlock *MBB) const { 1469 // We materialise the F128CSEL pseudo-instruction as some control flow and a 1470 // phi node: 1471 1472 // OrigBB: 1473 // [... previous instrs leading to comparison ...] 1474 // b.ne TrueBB 1475 // b EndBB 1476 // TrueBB: 1477 // ; Fallthrough 1478 // EndBB: 1479 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB] 1480 1481 MachineFunction *MF = MBB->getParent(); 1482 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1483 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 1484 DebugLoc DL = MI.getDebugLoc(); 1485 MachineFunction::iterator It = ++MBB->getIterator(); 1486 1487 Register DestReg = MI.getOperand(0).getReg(); 1488 Register IfTrueReg = MI.getOperand(1).getReg(); 1489 Register IfFalseReg = MI.getOperand(2).getReg(); 1490 unsigned CondCode = MI.getOperand(3).getImm(); 1491 bool NZCVKilled = MI.getOperand(4).isKill(); 1492 1493 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB); 1494 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB); 1495 MF->insert(It, TrueBB); 1496 MF->insert(It, EndBB); 1497 1498 // Transfer rest of current basic-block to EndBB 1499 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)), 1500 MBB->end()); 1501 EndBB->transferSuccessorsAndUpdatePHIs(MBB); 1502 1503 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB); 1504 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB); 1505 MBB->addSuccessor(TrueBB); 1506 MBB->addSuccessor(EndBB); 1507 1508 // TrueBB falls through to the end. 1509 TrueBB->addSuccessor(EndBB); 1510 1511 if (!NZCVKilled) { 1512 TrueBB->addLiveIn(AArch64::NZCV); 1513 EndBB->addLiveIn(AArch64::NZCV); 1514 } 1515 1516 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg) 1517 .addReg(IfTrueReg) 1518 .addMBB(TrueBB) 1519 .addReg(IfFalseReg) 1520 .addMBB(MBB); 1521 1522 MI.eraseFromParent(); 1523 return EndBB; 1524 } 1525 1526 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet( 1527 MachineInstr &MI, MachineBasicBlock *BB) const { 1528 assert(!isAsynchronousEHPersonality(classifyEHPersonality( 1529 BB->getParent()->getFunction().getPersonalityFn())) && 1530 "SEH does not use catchret!"); 1531 return BB; 1532 } 1533 1534 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter( 1535 MachineInstr &MI, MachineBasicBlock *BB) const { 1536 switch (MI.getOpcode()) { 1537 default: 1538 #ifndef NDEBUG 1539 MI.dump(); 1540 #endif 1541 llvm_unreachable("Unexpected instruction for custom inserter!"); 1542 1543 case AArch64::F128CSEL: 1544 return EmitF128CSEL(MI, BB); 1545 1546 case TargetOpcode::STACKMAP: 1547 case TargetOpcode::PATCHPOINT: 1548 return emitPatchPoint(MI, BB); 1549 1550 case AArch64::CATCHRET: 1551 return EmitLoweredCatchRet(MI, BB); 1552 } 1553 } 1554 1555 //===----------------------------------------------------------------------===// 1556 // AArch64 Lowering private implementation. 1557 //===----------------------------------------------------------------------===// 1558 1559 //===----------------------------------------------------------------------===// 1560 // Lowering Code 1561 //===----------------------------------------------------------------------===// 1562 1563 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64 1564 /// CC 1565 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) { 1566 switch (CC) { 1567 default: 1568 llvm_unreachable("Unknown condition code!"); 1569 case ISD::SETNE: 1570 return AArch64CC::NE; 1571 case ISD::SETEQ: 1572 return AArch64CC::EQ; 1573 case ISD::SETGT: 1574 return AArch64CC::GT; 1575 case ISD::SETGE: 1576 return AArch64CC::GE; 1577 case ISD::SETLT: 1578 return AArch64CC::LT; 1579 case ISD::SETLE: 1580 return AArch64CC::LE; 1581 case ISD::SETUGT: 1582 return AArch64CC::HI; 1583 case ISD::SETUGE: 1584 return AArch64CC::HS; 1585 case ISD::SETULT: 1586 return AArch64CC::LO; 1587 case ISD::SETULE: 1588 return AArch64CC::LS; 1589 } 1590 } 1591 1592 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC. 1593 static void changeFPCCToAArch64CC(ISD::CondCode CC, 1594 AArch64CC::CondCode &CondCode, 1595 AArch64CC::CondCode &CondCode2) { 1596 CondCode2 = AArch64CC::AL; 1597 switch (CC) { 1598 default: 1599 llvm_unreachable("Unknown FP condition!"); 1600 case ISD::SETEQ: 1601 case ISD::SETOEQ: 1602 CondCode = AArch64CC::EQ; 1603 break; 1604 case ISD::SETGT: 1605 case ISD::SETOGT: 1606 CondCode = AArch64CC::GT; 1607 break; 1608 case ISD::SETGE: 1609 case ISD::SETOGE: 1610 CondCode = AArch64CC::GE; 1611 break; 1612 case ISD::SETOLT: 1613 CondCode = AArch64CC::MI; 1614 break; 1615 case ISD::SETOLE: 1616 CondCode = AArch64CC::LS; 1617 break; 1618 case ISD::SETONE: 1619 CondCode = AArch64CC::MI; 1620 CondCode2 = AArch64CC::GT; 1621 break; 1622 case ISD::SETO: 1623 CondCode = AArch64CC::VC; 1624 break; 1625 case ISD::SETUO: 1626 CondCode = AArch64CC::VS; 1627 break; 1628 case ISD::SETUEQ: 1629 CondCode = AArch64CC::EQ; 1630 CondCode2 = AArch64CC::VS; 1631 break; 1632 case ISD::SETUGT: 1633 CondCode = AArch64CC::HI; 1634 break; 1635 case ISD::SETUGE: 1636 CondCode = AArch64CC::PL; 1637 break; 1638 case ISD::SETLT: 1639 case ISD::SETULT: 1640 CondCode = AArch64CC::LT; 1641 break; 1642 case ISD::SETLE: 1643 case ISD::SETULE: 1644 CondCode = AArch64CC::LE; 1645 break; 1646 case ISD::SETNE: 1647 case ISD::SETUNE: 1648 CondCode = AArch64CC::NE; 1649 break; 1650 } 1651 } 1652 1653 /// Convert a DAG fp condition code to an AArch64 CC. 1654 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that 1655 /// should be AND'ed instead of OR'ed. 1656 static void changeFPCCToANDAArch64CC(ISD::CondCode CC, 1657 AArch64CC::CondCode &CondCode, 1658 AArch64CC::CondCode &CondCode2) { 1659 CondCode2 = AArch64CC::AL; 1660 switch (CC) { 1661 default: 1662 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 1663 assert(CondCode2 == AArch64CC::AL); 1664 break; 1665 case ISD::SETONE: 1666 // (a one b) 1667 // == ((a olt b) || (a ogt b)) 1668 // == ((a ord b) && (a une b)) 1669 CondCode = AArch64CC::VC; 1670 CondCode2 = AArch64CC::NE; 1671 break; 1672 case ISD::SETUEQ: 1673 // (a ueq b) 1674 // == ((a uno b) || (a oeq b)) 1675 // == ((a ule b) && (a uge b)) 1676 CondCode = AArch64CC::PL; 1677 CondCode2 = AArch64CC::LE; 1678 break; 1679 } 1680 } 1681 1682 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 1683 /// CC usable with the vector instructions. Fewer operations are available 1684 /// without a real NZCV register, so we have to use less efficient combinations 1685 /// to get the same effect. 1686 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC, 1687 AArch64CC::CondCode &CondCode, 1688 AArch64CC::CondCode &CondCode2, 1689 bool &Invert) { 1690 Invert = false; 1691 switch (CC) { 1692 default: 1693 // Mostly the scalar mappings work fine. 1694 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 1695 break; 1696 case ISD::SETUO: 1697 Invert = true; 1698 LLVM_FALLTHROUGH; 1699 case ISD::SETO: 1700 CondCode = AArch64CC::MI; 1701 CondCode2 = AArch64CC::GE; 1702 break; 1703 case ISD::SETUEQ: 1704 case ISD::SETULT: 1705 case ISD::SETULE: 1706 case ISD::SETUGT: 1707 case ISD::SETUGE: 1708 // All of the compare-mask comparisons are ordered, but we can switch 1709 // between the two by a double inversion. E.g. ULE == !OGT. 1710 Invert = true; 1711 changeFPCCToAArch64CC(getSetCCInverse(CC, /* FP inverse */ MVT::f32), 1712 CondCode, CondCode2); 1713 break; 1714 } 1715 } 1716 1717 static bool isLegalArithImmed(uint64_t C) { 1718 // Matches AArch64DAGToDAGISel::SelectArithImmed(). 1719 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0); 1720 LLVM_DEBUG(dbgs() << "Is imm " << C 1721 << " legal: " << (IsLegal ? "yes\n" : "no\n")); 1722 return IsLegal; 1723 } 1724 1725 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on 1726 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags 1727 // can be set differently by this operation. It comes down to whether 1728 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then 1729 // everything is fine. If not then the optimization is wrong. Thus general 1730 // comparisons are only valid if op2 != 0. 1731 // 1732 // So, finally, the only LLVM-native comparisons that don't mention C and V 1733 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in 1734 // the absence of information about op2. 1735 static bool isCMN(SDValue Op, ISD::CondCode CC) { 1736 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) && 1737 (CC == ISD::SETEQ || CC == ISD::SETNE); 1738 } 1739 1740 static SDValue emitStrictFPComparison(SDValue LHS, SDValue RHS, const SDLoc &dl, 1741 SelectionDAG &DAG, SDValue Chain, 1742 bool IsSignaling) { 1743 EVT VT = LHS.getValueType(); 1744 assert(VT != MVT::f128); 1745 assert(VT != MVT::f16 && "Lowering of strict fp16 not yet implemented"); 1746 unsigned Opcode = 1747 IsSignaling ? AArch64ISD::STRICT_FCMPE : AArch64ISD::STRICT_FCMP; 1748 return DAG.getNode(Opcode, dl, {VT, MVT::Other}, {Chain, LHS, RHS}); 1749 } 1750 1751 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC, 1752 const SDLoc &dl, SelectionDAG &DAG) { 1753 EVT VT = LHS.getValueType(); 1754 const bool FullFP16 = 1755 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 1756 1757 if (VT.isFloatingPoint()) { 1758 assert(VT != MVT::f128); 1759 if (VT == MVT::f16 && !FullFP16) { 1760 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 1761 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 1762 VT = MVT::f32; 1763 } 1764 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS); 1765 } 1766 1767 // The CMP instruction is just an alias for SUBS, and representing it as 1768 // SUBS means that it's possible to get CSE with subtract operations. 1769 // A later phase can perform the optimization of setting the destination 1770 // register to WZR/XZR if it ends up being unused. 1771 unsigned Opcode = AArch64ISD::SUBS; 1772 1773 if (isCMN(RHS, CC)) { 1774 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ? 1775 Opcode = AArch64ISD::ADDS; 1776 RHS = RHS.getOperand(1); 1777 } else if (isCMN(LHS, CC)) { 1778 // As we are looking for EQ/NE compares, the operands can be commuted ; can 1779 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ? 1780 Opcode = AArch64ISD::ADDS; 1781 LHS = LHS.getOperand(1); 1782 } else if (isNullConstant(RHS) && !isUnsignedIntSetCC(CC)) { 1783 if (LHS.getOpcode() == ISD::AND) { 1784 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST 1785 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one 1786 // of the signed comparisons. 1787 const SDValue ANDSNode = DAG.getNode(AArch64ISD::ANDS, dl, 1788 DAG.getVTList(VT, MVT_CC), 1789 LHS.getOperand(0), 1790 LHS.getOperand(1)); 1791 // Replace all users of (and X, Y) with newly generated (ands X, Y) 1792 DAG.ReplaceAllUsesWith(LHS, ANDSNode); 1793 return ANDSNode.getValue(1); 1794 } else if (LHS.getOpcode() == AArch64ISD::ANDS) { 1795 // Use result of ANDS 1796 return LHS.getValue(1); 1797 } 1798 } 1799 1800 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS) 1801 .getValue(1); 1802 } 1803 1804 /// \defgroup AArch64CCMP CMP;CCMP matching 1805 /// 1806 /// These functions deal with the formation of CMP;CCMP;... sequences. 1807 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of 1808 /// a comparison. They set the NZCV flags to a predefined value if their 1809 /// predicate is false. This allows to express arbitrary conjunctions, for 1810 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))" 1811 /// expressed as: 1812 /// cmp A 1813 /// ccmp B, inv(CB), CA 1814 /// check for CB flags 1815 /// 1816 /// This naturally lets us implement chains of AND operations with SETCC 1817 /// operands. And we can even implement some other situations by transforming 1818 /// them: 1819 /// - We can implement (NEG SETCC) i.e. negating a single comparison by 1820 /// negating the flags used in a CCMP/FCCMP operations. 1821 /// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations 1822 /// by negating the flags we test for afterwards. i.e. 1823 /// NEG (CMP CCMP CCCMP ...) can be implemented. 1824 /// - Note that we can only ever negate all previously processed results. 1825 /// What we can not implement by flipping the flags to test is a negation 1826 /// of two sub-trees (because the negation affects all sub-trees emitted so 1827 /// far, so the 2nd sub-tree we emit would also affect the first). 1828 /// With those tools we can implement some OR operations: 1829 /// - (OR (SETCC A) (SETCC B)) can be implemented via: 1830 /// NEG (AND (NEG (SETCC A)) (NEG (SETCC B))) 1831 /// - After transforming OR to NEG/AND combinations we may be able to use NEG 1832 /// elimination rules from earlier to implement the whole thing as a 1833 /// CCMP/FCCMP chain. 1834 /// 1835 /// As complete example: 1836 /// or (or (setCA (cmp A)) (setCB (cmp B))) 1837 /// (and (setCC (cmp C)) (setCD (cmp D)))" 1838 /// can be reassociated to: 1839 /// or (and (setCC (cmp C)) setCD (cmp D)) 1840 // (or (setCA (cmp A)) (setCB (cmp B))) 1841 /// can be transformed to: 1842 /// not (and (not (and (setCC (cmp C)) (setCD (cmp D)))) 1843 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))" 1844 /// which can be implemented as: 1845 /// cmp C 1846 /// ccmp D, inv(CD), CC 1847 /// ccmp A, CA, inv(CD) 1848 /// ccmp B, CB, inv(CA) 1849 /// check for CB flags 1850 /// 1851 /// A counterexample is "or (and A B) (and C D)" which translates to 1852 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we 1853 /// can only implement 1 of the inner (not) operations, but not both! 1854 /// @{ 1855 1856 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate. 1857 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS, 1858 ISD::CondCode CC, SDValue CCOp, 1859 AArch64CC::CondCode Predicate, 1860 AArch64CC::CondCode OutCC, 1861 const SDLoc &DL, SelectionDAG &DAG) { 1862 unsigned Opcode = 0; 1863 const bool FullFP16 = 1864 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 1865 1866 if (LHS.getValueType().isFloatingPoint()) { 1867 assert(LHS.getValueType() != MVT::f128); 1868 if (LHS.getValueType() == MVT::f16 && !FullFP16) { 1869 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS); 1870 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS); 1871 } 1872 Opcode = AArch64ISD::FCCMP; 1873 } else if (RHS.getOpcode() == ISD::SUB) { 1874 SDValue SubOp0 = RHS.getOperand(0); 1875 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 1876 // See emitComparison() on why we can only do this for SETEQ and SETNE. 1877 Opcode = AArch64ISD::CCMN; 1878 RHS = RHS.getOperand(1); 1879 } 1880 } 1881 if (Opcode == 0) 1882 Opcode = AArch64ISD::CCMP; 1883 1884 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC); 1885 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC); 1886 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC); 1887 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32); 1888 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp); 1889 } 1890 1891 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be 1892 /// expressed as a conjunction. See \ref AArch64CCMP. 1893 /// \param CanNegate Set to true if we can negate the whole sub-tree just by 1894 /// changing the conditions on the SETCC tests. 1895 /// (this means we can call emitConjunctionRec() with 1896 /// Negate==true on this sub-tree) 1897 /// \param MustBeFirst Set to true if this subtree needs to be negated and we 1898 /// cannot do the negation naturally. We are required to 1899 /// emit the subtree first in this case. 1900 /// \param WillNegate Is true if are called when the result of this 1901 /// subexpression must be negated. This happens when the 1902 /// outer expression is an OR. We can use this fact to know 1903 /// that we have a double negation (or (or ...) ...) that 1904 /// can be implemented for free. 1905 static bool canEmitConjunction(const SDValue Val, bool &CanNegate, 1906 bool &MustBeFirst, bool WillNegate, 1907 unsigned Depth = 0) { 1908 if (!Val.hasOneUse()) 1909 return false; 1910 unsigned Opcode = Val->getOpcode(); 1911 if (Opcode == ISD::SETCC) { 1912 if (Val->getOperand(0).getValueType() == MVT::f128) 1913 return false; 1914 CanNegate = true; 1915 MustBeFirst = false; 1916 return true; 1917 } 1918 // Protect against exponential runtime and stack overflow. 1919 if (Depth > 6) 1920 return false; 1921 if (Opcode == ISD::AND || Opcode == ISD::OR) { 1922 bool IsOR = Opcode == ISD::OR; 1923 SDValue O0 = Val->getOperand(0); 1924 SDValue O1 = Val->getOperand(1); 1925 bool CanNegateL; 1926 bool MustBeFirstL; 1927 if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1)) 1928 return false; 1929 bool CanNegateR; 1930 bool MustBeFirstR; 1931 if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1)) 1932 return false; 1933 1934 if (MustBeFirstL && MustBeFirstR) 1935 return false; 1936 1937 if (IsOR) { 1938 // For an OR expression we need to be able to naturally negate at least 1939 // one side or we cannot do the transformation at all. 1940 if (!CanNegateL && !CanNegateR) 1941 return false; 1942 // If we the result of the OR will be negated and we can naturally negate 1943 // the leafs, then this sub-tree as a whole negates naturally. 1944 CanNegate = WillNegate && CanNegateL && CanNegateR; 1945 // If we cannot naturally negate the whole sub-tree, then this must be 1946 // emitted first. 1947 MustBeFirst = !CanNegate; 1948 } else { 1949 assert(Opcode == ISD::AND && "Must be OR or AND"); 1950 // We cannot naturally negate an AND operation. 1951 CanNegate = false; 1952 MustBeFirst = MustBeFirstL || MustBeFirstR; 1953 } 1954 return true; 1955 } 1956 return false; 1957 } 1958 1959 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain 1960 /// of CCMP/CFCMP ops. See @ref AArch64CCMP. 1961 /// Tries to transform the given i1 producing node @p Val to a series compare 1962 /// and conditional compare operations. @returns an NZCV flags producing node 1963 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if 1964 /// transformation was not possible. 1965 /// \p Negate is true if we want this sub-tree being negated just by changing 1966 /// SETCC conditions. 1967 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val, 1968 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp, 1969 AArch64CC::CondCode Predicate) { 1970 // We're at a tree leaf, produce a conditional comparison operation. 1971 unsigned Opcode = Val->getOpcode(); 1972 if (Opcode == ISD::SETCC) { 1973 SDValue LHS = Val->getOperand(0); 1974 SDValue RHS = Val->getOperand(1); 1975 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get(); 1976 bool isInteger = LHS.getValueType().isInteger(); 1977 if (Negate) 1978 CC = getSetCCInverse(CC, LHS.getValueType()); 1979 SDLoc DL(Val); 1980 // Determine OutCC and handle FP special case. 1981 if (isInteger) { 1982 OutCC = changeIntCCToAArch64CC(CC); 1983 } else { 1984 assert(LHS.getValueType().isFloatingPoint()); 1985 AArch64CC::CondCode ExtraCC; 1986 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC); 1987 // Some floating point conditions can't be tested with a single condition 1988 // code. Construct an additional comparison in this case. 1989 if (ExtraCC != AArch64CC::AL) { 1990 SDValue ExtraCmp; 1991 if (!CCOp.getNode()) 1992 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG); 1993 else 1994 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, 1995 ExtraCC, DL, DAG); 1996 CCOp = ExtraCmp; 1997 Predicate = ExtraCC; 1998 } 1999 } 2000 2001 // Produce a normal comparison if we are first in the chain 2002 if (!CCOp) 2003 return emitComparison(LHS, RHS, CC, DL, DAG); 2004 // Otherwise produce a ccmp. 2005 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL, 2006 DAG); 2007 } 2008 assert(Val->hasOneUse() && "Valid conjunction/disjunction tree"); 2009 2010 bool IsOR = Opcode == ISD::OR; 2011 2012 SDValue LHS = Val->getOperand(0); 2013 bool CanNegateL; 2014 bool MustBeFirstL; 2015 bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR); 2016 assert(ValidL && "Valid conjunction/disjunction tree"); 2017 (void)ValidL; 2018 2019 SDValue RHS = Val->getOperand(1); 2020 bool CanNegateR; 2021 bool MustBeFirstR; 2022 bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR); 2023 assert(ValidR && "Valid conjunction/disjunction tree"); 2024 (void)ValidR; 2025 2026 // Swap sub-tree that must come first to the right side. 2027 if (MustBeFirstL) { 2028 assert(!MustBeFirstR && "Valid conjunction/disjunction tree"); 2029 std::swap(LHS, RHS); 2030 std::swap(CanNegateL, CanNegateR); 2031 std::swap(MustBeFirstL, MustBeFirstR); 2032 } 2033 2034 bool NegateR; 2035 bool NegateAfterR; 2036 bool NegateL; 2037 bool NegateAfterAll; 2038 if (Opcode == ISD::OR) { 2039 // Swap the sub-tree that we can negate naturally to the left. 2040 if (!CanNegateL) { 2041 assert(CanNegateR && "at least one side must be negatable"); 2042 assert(!MustBeFirstR && "invalid conjunction/disjunction tree"); 2043 assert(!Negate); 2044 std::swap(LHS, RHS); 2045 NegateR = false; 2046 NegateAfterR = true; 2047 } else { 2048 // Negate the left sub-tree if possible, otherwise negate the result. 2049 NegateR = CanNegateR; 2050 NegateAfterR = !CanNegateR; 2051 } 2052 NegateL = true; 2053 NegateAfterAll = !Negate; 2054 } else { 2055 assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree"); 2056 assert(!Negate && "Valid conjunction/disjunction tree"); 2057 2058 NegateL = false; 2059 NegateR = false; 2060 NegateAfterR = false; 2061 NegateAfterAll = false; 2062 } 2063 2064 // Emit sub-trees. 2065 AArch64CC::CondCode RHSCC; 2066 SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate); 2067 if (NegateAfterR) 2068 RHSCC = AArch64CC::getInvertedCondCode(RHSCC); 2069 SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC); 2070 if (NegateAfterAll) 2071 OutCC = AArch64CC::getInvertedCondCode(OutCC); 2072 return CmpL; 2073 } 2074 2075 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops). 2076 /// In some cases this is even possible with OR operations in the expression. 2077 /// See \ref AArch64CCMP. 2078 /// \see emitConjunctionRec(). 2079 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val, 2080 AArch64CC::CondCode &OutCC) { 2081 bool DummyCanNegate; 2082 bool DummyMustBeFirst; 2083 if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false)) 2084 return SDValue(); 2085 2086 return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL); 2087 } 2088 2089 /// @} 2090 2091 /// Returns how profitable it is to fold a comparison's operand's shift and/or 2092 /// extension operations. 2093 static unsigned getCmpOperandFoldingProfit(SDValue Op) { 2094 auto isSupportedExtend = [&](SDValue V) { 2095 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG) 2096 return true; 2097 2098 if (V.getOpcode() == ISD::AND) 2099 if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 2100 uint64_t Mask = MaskCst->getZExtValue(); 2101 return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF); 2102 } 2103 2104 return false; 2105 }; 2106 2107 if (!Op.hasOneUse()) 2108 return 0; 2109 2110 if (isSupportedExtend(Op)) 2111 return 1; 2112 2113 unsigned Opc = Op.getOpcode(); 2114 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA) 2115 if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 2116 uint64_t Shift = ShiftCst->getZExtValue(); 2117 if (isSupportedExtend(Op.getOperand(0))) 2118 return (Shift <= 4) ? 2 : 1; 2119 EVT VT = Op.getValueType(); 2120 if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63)) 2121 return 1; 2122 } 2123 2124 return 0; 2125 } 2126 2127 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 2128 SDValue &AArch64cc, SelectionDAG &DAG, 2129 const SDLoc &dl) { 2130 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 2131 EVT VT = RHS.getValueType(); 2132 uint64_t C = RHSC->getZExtValue(); 2133 if (!isLegalArithImmed(C)) { 2134 // Constant does not fit, try adjusting it by one? 2135 switch (CC) { 2136 default: 2137 break; 2138 case ISD::SETLT: 2139 case ISD::SETGE: 2140 if ((VT == MVT::i32 && C != 0x80000000 && 2141 isLegalArithImmed((uint32_t)(C - 1))) || 2142 (VT == MVT::i64 && C != 0x80000000ULL && 2143 isLegalArithImmed(C - 1ULL))) { 2144 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 2145 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 2146 RHS = DAG.getConstant(C, dl, VT); 2147 } 2148 break; 2149 case ISD::SETULT: 2150 case ISD::SETUGE: 2151 if ((VT == MVT::i32 && C != 0 && 2152 isLegalArithImmed((uint32_t)(C - 1))) || 2153 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) { 2154 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 2155 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 2156 RHS = DAG.getConstant(C, dl, VT); 2157 } 2158 break; 2159 case ISD::SETLE: 2160 case ISD::SETGT: 2161 if ((VT == MVT::i32 && C != INT32_MAX && 2162 isLegalArithImmed((uint32_t)(C + 1))) || 2163 (VT == MVT::i64 && C != INT64_MAX && 2164 isLegalArithImmed(C + 1ULL))) { 2165 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 2166 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 2167 RHS = DAG.getConstant(C, dl, VT); 2168 } 2169 break; 2170 case ISD::SETULE: 2171 case ISD::SETUGT: 2172 if ((VT == MVT::i32 && C != UINT32_MAX && 2173 isLegalArithImmed((uint32_t)(C + 1))) || 2174 (VT == MVT::i64 && C != UINT64_MAX && 2175 isLegalArithImmed(C + 1ULL))) { 2176 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 2177 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 2178 RHS = DAG.getConstant(C, dl, VT); 2179 } 2180 break; 2181 } 2182 } 2183 } 2184 2185 // Comparisons are canonicalized so that the RHS operand is simpler than the 2186 // LHS one, the extreme case being when RHS is an immediate. However, AArch64 2187 // can fold some shift+extend operations on the RHS operand, so swap the 2188 // operands if that can be done. 2189 // 2190 // For example: 2191 // lsl w13, w11, #1 2192 // cmp w13, w12 2193 // can be turned into: 2194 // cmp w12, w11, lsl #1 2195 if (!isa<ConstantSDNode>(RHS) || 2196 !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) { 2197 SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS; 2198 2199 if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) { 2200 std::swap(LHS, RHS); 2201 CC = ISD::getSetCCSwappedOperands(CC); 2202 } 2203 } 2204 2205 SDValue Cmp; 2206 AArch64CC::CondCode AArch64CC; 2207 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) { 2208 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS); 2209 2210 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095. 2211 // For the i8 operand, the largest immediate is 255, so this can be easily 2212 // encoded in the compare instruction. For the i16 operand, however, the 2213 // largest immediate cannot be encoded in the compare. 2214 // Therefore, use a sign extending load and cmn to avoid materializing the 2215 // -1 constant. For example, 2216 // movz w1, #65535 2217 // ldrh w0, [x0, #0] 2218 // cmp w0, w1 2219 // > 2220 // ldrsh w0, [x0, #0] 2221 // cmn w0, #1 2222 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS) 2223 // if and only if (sext LHS) == (sext RHS). The checks are in place to 2224 // ensure both the LHS and RHS are truly zero extended and to make sure the 2225 // transformation is profitable. 2226 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) && 2227 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD && 2228 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 && 2229 LHS.getNode()->hasNUsesOfValue(1, 0)) { 2230 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue(); 2231 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) { 2232 SDValue SExt = 2233 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS, 2234 DAG.getValueType(MVT::i16)); 2235 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl, 2236 RHS.getValueType()), 2237 CC, dl, DAG); 2238 AArch64CC = changeIntCCToAArch64CC(CC); 2239 } 2240 } 2241 2242 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) { 2243 if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) { 2244 if ((CC == ISD::SETNE) ^ RHSC->isNullValue()) 2245 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC); 2246 } 2247 } 2248 } 2249 2250 if (!Cmp) { 2251 Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 2252 AArch64CC = changeIntCCToAArch64CC(CC); 2253 } 2254 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC); 2255 return Cmp; 2256 } 2257 2258 static std::pair<SDValue, SDValue> 2259 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) { 2260 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) && 2261 "Unsupported value type"); 2262 SDValue Value, Overflow; 2263 SDLoc DL(Op); 2264 SDValue LHS = Op.getOperand(0); 2265 SDValue RHS = Op.getOperand(1); 2266 unsigned Opc = 0; 2267 switch (Op.getOpcode()) { 2268 default: 2269 llvm_unreachable("Unknown overflow instruction!"); 2270 case ISD::SADDO: 2271 Opc = AArch64ISD::ADDS; 2272 CC = AArch64CC::VS; 2273 break; 2274 case ISD::UADDO: 2275 Opc = AArch64ISD::ADDS; 2276 CC = AArch64CC::HS; 2277 break; 2278 case ISD::SSUBO: 2279 Opc = AArch64ISD::SUBS; 2280 CC = AArch64CC::VS; 2281 break; 2282 case ISD::USUBO: 2283 Opc = AArch64ISD::SUBS; 2284 CC = AArch64CC::LO; 2285 break; 2286 // Multiply needs a little bit extra work. 2287 case ISD::SMULO: 2288 case ISD::UMULO: { 2289 CC = AArch64CC::NE; 2290 bool IsSigned = Op.getOpcode() == ISD::SMULO; 2291 if (Op.getValueType() == MVT::i32) { 2292 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 2293 // For a 32 bit multiply with overflow check we want the instruction 2294 // selector to generate a widening multiply (SMADDL/UMADDL). For that we 2295 // need to generate the following pattern: 2296 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b)) 2297 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS); 2298 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS); 2299 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 2300 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul, 2301 DAG.getConstant(0, DL, MVT::i64)); 2302 // On AArch64 the upper 32 bits are always zero extended for a 32 bit 2303 // operation. We need to clear out the upper 32 bits, because we used a 2304 // widening multiply that wrote all 64 bits. In the end this should be a 2305 // noop. 2306 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add); 2307 if (IsSigned) { 2308 // The signed overflow check requires more than just a simple check for 2309 // any bit set in the upper 32 bits of the result. These bits could be 2310 // just the sign bits of a negative number. To perform the overflow 2311 // check we have to arithmetic shift right the 32nd bit of the result by 2312 // 31 bits. Then we compare the result to the upper 32 bits. 2313 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add, 2314 DAG.getConstant(32, DL, MVT::i64)); 2315 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits); 2316 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value, 2317 DAG.getConstant(31, DL, MVT::i64)); 2318 // It is important that LowerBits is last, otherwise the arithmetic 2319 // shift will not be folded into the compare (SUBS). 2320 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32); 2321 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 2322 .getValue(1); 2323 } else { 2324 // The overflow check for unsigned multiply is easy. We only need to 2325 // check if any of the upper 32 bits are set. This can be done with a 2326 // CMP (shifted register). For that we need to generate the following 2327 // pattern: 2328 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32) 2329 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul, 2330 DAG.getConstant(32, DL, MVT::i64)); 2331 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 2332 Overflow = 2333 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 2334 DAG.getConstant(0, DL, MVT::i64), 2335 UpperBits).getValue(1); 2336 } 2337 break; 2338 } 2339 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type"); 2340 // For the 64 bit multiply 2341 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 2342 if (IsSigned) { 2343 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS); 2344 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value, 2345 DAG.getConstant(63, DL, MVT::i64)); 2346 // It is important that LowerBits is last, otherwise the arithmetic 2347 // shift will not be folded into the compare (SUBS). 2348 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 2349 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 2350 .getValue(1); 2351 } else { 2352 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS); 2353 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 2354 Overflow = 2355 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 2356 DAG.getConstant(0, DL, MVT::i64), 2357 UpperBits).getValue(1); 2358 } 2359 break; 2360 } 2361 } // switch (...) 2362 2363 if (Opc) { 2364 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32); 2365 2366 // Emit the AArch64 operation with overflow check. 2367 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS); 2368 Overflow = Value.getValue(1); 2369 } 2370 return std::make_pair(Value, Overflow); 2371 } 2372 2373 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG, 2374 RTLIB::Libcall Call) const { 2375 bool IsStrict = Op->isStrictFPOpcode(); 2376 unsigned Offset = IsStrict ? 1 : 0; 2377 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 2378 SmallVector<SDValue, 2> Ops(Op->op_begin() + Offset, Op->op_end()); 2379 MakeLibCallOptions CallOptions; 2380 SDValue Result; 2381 SDLoc dl(Op); 2382 std::tie(Result, Chain) = makeLibCall(DAG, Call, Op.getValueType(), Ops, 2383 CallOptions, dl, Chain); 2384 return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result; 2385 } 2386 2387 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) { 2388 SDValue Sel = Op.getOperand(0); 2389 SDValue Other = Op.getOperand(1); 2390 SDLoc dl(Sel); 2391 2392 // If the operand is an overflow checking operation, invert the condition 2393 // code and kill the Not operation. I.e., transform: 2394 // (xor (overflow_op_bool, 1)) 2395 // --> 2396 // (csel 1, 0, invert(cc), overflow_op_bool) 2397 // ... which later gets transformed to just a cset instruction with an 2398 // inverted condition code, rather than a cset + eor sequence. 2399 if (isOneConstant(Other) && ISD::isOverflowIntrOpRes(Sel)) { 2400 // Only lower legal XALUO ops. 2401 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0))) 2402 return SDValue(); 2403 2404 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 2405 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 2406 AArch64CC::CondCode CC; 2407 SDValue Value, Overflow; 2408 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG); 2409 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); 2410 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal, 2411 CCVal, Overflow); 2412 } 2413 // If neither operand is a SELECT_CC, give up. 2414 if (Sel.getOpcode() != ISD::SELECT_CC) 2415 std::swap(Sel, Other); 2416 if (Sel.getOpcode() != ISD::SELECT_CC) 2417 return Op; 2418 2419 // The folding we want to perform is: 2420 // (xor x, (select_cc a, b, cc, 0, -1) ) 2421 // --> 2422 // (csel x, (xor x, -1), cc ...) 2423 // 2424 // The latter will get matched to a CSINV instruction. 2425 2426 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get(); 2427 SDValue LHS = Sel.getOperand(0); 2428 SDValue RHS = Sel.getOperand(1); 2429 SDValue TVal = Sel.getOperand(2); 2430 SDValue FVal = Sel.getOperand(3); 2431 2432 // FIXME: This could be generalized to non-integer comparisons. 2433 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 2434 return Op; 2435 2436 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 2437 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 2438 2439 // The values aren't constants, this isn't the pattern we're looking for. 2440 if (!CFVal || !CTVal) 2441 return Op; 2442 2443 // We can commute the SELECT_CC by inverting the condition. This 2444 // might be needed to make this fit into a CSINV pattern. 2445 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) { 2446 std::swap(TVal, FVal); 2447 std::swap(CTVal, CFVal); 2448 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 2449 } 2450 2451 // If the constants line up, perform the transform! 2452 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) { 2453 SDValue CCVal; 2454 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 2455 2456 FVal = Other; 2457 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other, 2458 DAG.getConstant(-1ULL, dl, Other.getValueType())); 2459 2460 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal, 2461 CCVal, Cmp); 2462 } 2463 2464 return Op; 2465 } 2466 2467 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 2468 EVT VT = Op.getValueType(); 2469 2470 // Let legalize expand this if it isn't a legal type yet. 2471 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 2472 return SDValue(); 2473 2474 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 2475 2476 unsigned Opc; 2477 bool ExtraOp = false; 2478 switch (Op.getOpcode()) { 2479 default: 2480 llvm_unreachable("Invalid code"); 2481 case ISD::ADDC: 2482 Opc = AArch64ISD::ADDS; 2483 break; 2484 case ISD::SUBC: 2485 Opc = AArch64ISD::SUBS; 2486 break; 2487 case ISD::ADDE: 2488 Opc = AArch64ISD::ADCS; 2489 ExtraOp = true; 2490 break; 2491 case ISD::SUBE: 2492 Opc = AArch64ISD::SBCS; 2493 ExtraOp = true; 2494 break; 2495 } 2496 2497 if (!ExtraOp) 2498 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1)); 2499 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1), 2500 Op.getOperand(2)); 2501 } 2502 2503 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) { 2504 // Let legalize expand this if it isn't a legal type yet. 2505 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 2506 return SDValue(); 2507 2508 SDLoc dl(Op); 2509 AArch64CC::CondCode CC; 2510 // The actual operation that sets the overflow or carry flag. 2511 SDValue Value, Overflow; 2512 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG); 2513 2514 // We use 0 and 1 as false and true values. 2515 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 2516 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 2517 2518 // We use an inverted condition, because the conditional select is inverted 2519 // too. This will allow it to be selected to a single instruction: 2520 // CSINC Wd, WZR, WZR, invert(cond). 2521 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); 2522 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal, 2523 CCVal, Overflow); 2524 2525 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 2526 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 2527 } 2528 2529 // Prefetch operands are: 2530 // 1: Address to prefetch 2531 // 2: bool isWrite 2532 // 3: int locality (0 = no locality ... 3 = extreme locality) 2533 // 4: bool isDataCache 2534 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) { 2535 SDLoc DL(Op); 2536 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 2537 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 2538 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 2539 2540 bool IsStream = !Locality; 2541 // When the locality number is set 2542 if (Locality) { 2543 // The front-end should have filtered out the out-of-range values 2544 assert(Locality <= 3 && "Prefetch locality out-of-range"); 2545 // The locality degree is the opposite of the cache speed. 2546 // Put the number the other way around. 2547 // The encoding starts at 0 for level 1 2548 Locality = 3 - Locality; 2549 } 2550 2551 // built the mask value encoding the expected behavior. 2552 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit 2553 (!IsData << 3) | // IsDataCache bit 2554 (Locality << 1) | // Cache level bits 2555 (unsigned)IsStream; // Stream bit 2556 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0), 2557 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1)); 2558 } 2559 2560 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op, 2561 SelectionDAG &DAG) const { 2562 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering"); 2563 2564 RTLIB::Libcall LC; 2565 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 2566 2567 return LowerF128Call(Op, DAG, LC); 2568 } 2569 2570 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op, 2571 SelectionDAG &DAG) const { 2572 bool IsStrict = Op->isStrictFPOpcode(); 2573 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 2574 if (SrcVal.getValueType() != MVT::f128) { 2575 // It's legal except when f128 is involved 2576 return Op; 2577 } 2578 2579 RTLIB::Libcall LC; 2580 LC = RTLIB::getFPROUND(SrcVal.getValueType(), Op.getValueType()); 2581 2582 // FP_ROUND node has a second operand indicating whether it is known to be 2583 // precise. That doesn't take part in the LibCall so we can't directly use 2584 // LowerF128Call. 2585 MakeLibCallOptions CallOptions; 2586 SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue(); 2587 SDValue Result; 2588 SDLoc dl(Op); 2589 std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal, 2590 CallOptions, dl, Chain); 2591 return IsStrict ? DAG.getMergeValues({Result, Chain}, dl) : Result; 2592 } 2593 2594 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op, 2595 SelectionDAG &DAG) const { 2596 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 2597 // Any additional optimization in this function should be recorded 2598 // in the cost tables. 2599 EVT InVT = Op.getOperand(0).getValueType(); 2600 EVT VT = Op.getValueType(); 2601 unsigned NumElts = InVT.getVectorNumElements(); 2602 2603 // f16 conversions are promoted to f32 when full fp16 is not supported. 2604 if (InVT.getVectorElementType() == MVT::f16 && 2605 !Subtarget->hasFullFP16()) { 2606 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts); 2607 SDLoc dl(Op); 2608 return DAG.getNode( 2609 Op.getOpcode(), dl, Op.getValueType(), 2610 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0))); 2611 } 2612 2613 if (VT.getSizeInBits() < InVT.getSizeInBits()) { 2614 SDLoc dl(Op); 2615 SDValue Cv = 2616 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(), 2617 Op.getOperand(0)); 2618 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv); 2619 } 2620 2621 if (VT.getSizeInBits() > InVT.getSizeInBits()) { 2622 SDLoc dl(Op); 2623 MVT ExtVT = 2624 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()), 2625 VT.getVectorNumElements()); 2626 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0)); 2627 return DAG.getNode(Op.getOpcode(), dl, VT, Ext); 2628 } 2629 2630 // Type changing conversions are illegal. 2631 return Op; 2632 } 2633 2634 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op, 2635 SelectionDAG &DAG) const { 2636 bool IsStrict = Op->isStrictFPOpcode(); 2637 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 2638 2639 if (SrcVal.getValueType().isVector()) 2640 return LowerVectorFP_TO_INT(Op, DAG); 2641 2642 // f16 conversions are promoted to f32 when full fp16 is not supported. 2643 if (SrcVal.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) { 2644 assert(!IsStrict && "Lowering of strict fp16 not yet implemented"); 2645 SDLoc dl(Op); 2646 return DAG.getNode( 2647 Op.getOpcode(), dl, Op.getValueType(), 2648 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, SrcVal)); 2649 } 2650 2651 if (SrcVal.getValueType() != MVT::f128) { 2652 // It's legal except when f128 is involved 2653 return Op; 2654 } 2655 2656 RTLIB::Libcall LC; 2657 if (Op.getOpcode() == ISD::FP_TO_SINT || 2658 Op.getOpcode() == ISD::STRICT_FP_TO_SINT) 2659 LC = RTLIB::getFPTOSINT(SrcVal.getValueType(), Op.getValueType()); 2660 else 2661 LC = RTLIB::getFPTOUINT(SrcVal.getValueType(), Op.getValueType()); 2662 2663 return LowerF128Call(Op, DAG, LC); 2664 } 2665 2666 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 2667 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 2668 // Any additional optimization in this function should be recorded 2669 // in the cost tables. 2670 EVT VT = Op.getValueType(); 2671 SDLoc dl(Op); 2672 SDValue In = Op.getOperand(0); 2673 EVT InVT = In.getValueType(); 2674 2675 if (VT.getSizeInBits() < InVT.getSizeInBits()) { 2676 MVT CastVT = 2677 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()), 2678 InVT.getVectorNumElements()); 2679 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In); 2680 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl)); 2681 } 2682 2683 if (VT.getSizeInBits() > InVT.getSizeInBits()) { 2684 unsigned CastOpc = 2685 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 2686 EVT CastVT = VT.changeVectorElementTypeToInteger(); 2687 In = DAG.getNode(CastOpc, dl, CastVT, In); 2688 return DAG.getNode(Op.getOpcode(), dl, VT, In); 2689 } 2690 2691 return Op; 2692 } 2693 2694 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op, 2695 SelectionDAG &DAG) const { 2696 if (Op.getValueType().isVector()) 2697 return LowerVectorINT_TO_FP(Op, DAG); 2698 2699 bool IsStrict = Op->isStrictFPOpcode(); 2700 SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0); 2701 2702 // f16 conversions are promoted to f32 when full fp16 is not supported. 2703 if (Op.getValueType() == MVT::f16 && 2704 !Subtarget->hasFullFP16()) { 2705 assert(!IsStrict && "Lowering of strict fp16 not yet implemented"); 2706 SDLoc dl(Op); 2707 return DAG.getNode( 2708 ISD::FP_ROUND, dl, MVT::f16, 2709 DAG.getNode(Op.getOpcode(), dl, MVT::f32, SrcVal), 2710 DAG.getIntPtrConstant(0, dl)); 2711 } 2712 2713 // i128 conversions are libcalls. 2714 if (SrcVal.getValueType() == MVT::i128) 2715 return SDValue(); 2716 2717 // Other conversions are legal, unless it's to the completely software-based 2718 // fp128. 2719 if (Op.getValueType() != MVT::f128) 2720 return Op; 2721 2722 RTLIB::Libcall LC; 2723 if (Op.getOpcode() == ISD::SINT_TO_FP || 2724 Op.getOpcode() == ISD::STRICT_SINT_TO_FP) 2725 LC = RTLIB::getSINTTOFP(SrcVal.getValueType(), Op.getValueType()); 2726 else 2727 LC = RTLIB::getUINTTOFP(SrcVal.getValueType(), Op.getValueType()); 2728 2729 return LowerF128Call(Op, DAG, LC); 2730 } 2731 2732 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op, 2733 SelectionDAG &DAG) const { 2734 // For iOS, we want to call an alternative entry point: __sincos_stret, 2735 // which returns the values in two S / D registers. 2736 SDLoc dl(Op); 2737 SDValue Arg = Op.getOperand(0); 2738 EVT ArgVT = Arg.getValueType(); 2739 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 2740 2741 ArgListTy Args; 2742 ArgListEntry Entry; 2743 2744 Entry.Node = Arg; 2745 Entry.Ty = ArgTy; 2746 Entry.IsSExt = false; 2747 Entry.IsZExt = false; 2748 Args.push_back(Entry); 2749 2750 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64 2751 : RTLIB::SINCOS_STRET_F32; 2752 const char *LibcallName = getLibcallName(LC); 2753 SDValue Callee = 2754 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout())); 2755 2756 StructType *RetTy = StructType::get(ArgTy, ArgTy); 2757 TargetLowering::CallLoweringInfo CLI(DAG); 2758 CLI.setDebugLoc(dl) 2759 .setChain(DAG.getEntryNode()) 2760 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args)); 2761 2762 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2763 return CallResult.first; 2764 } 2765 2766 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) { 2767 if (Op.getValueType() != MVT::f16) 2768 return SDValue(); 2769 2770 assert(Op.getOperand(0).getValueType() == MVT::i16); 2771 SDLoc DL(Op); 2772 2773 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0)); 2774 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op); 2775 return SDValue( 2776 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op, 2777 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 2778 0); 2779 } 2780 2781 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 2782 if (OrigVT.getSizeInBits() >= 64) 2783 return OrigVT; 2784 2785 assert(OrigVT.isSimple() && "Expecting a simple value type"); 2786 2787 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 2788 switch (OrigSimpleTy) { 2789 default: llvm_unreachable("Unexpected Vector Type"); 2790 case MVT::v2i8: 2791 case MVT::v2i16: 2792 return MVT::v2i32; 2793 case MVT::v4i8: 2794 return MVT::v4i16; 2795 } 2796 } 2797 2798 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG, 2799 const EVT &OrigTy, 2800 const EVT &ExtTy, 2801 unsigned ExtOpcode) { 2802 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 2803 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 2804 // 64-bits we need to insert a new extension so that it will be 64-bits. 2805 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 2806 if (OrigTy.getSizeInBits() >= 64) 2807 return N; 2808 2809 // Must extend size to at least 64 bits to be used as an operand for VMULL. 2810 EVT NewVT = getExtensionTo64Bits(OrigTy); 2811 2812 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 2813 } 2814 2815 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 2816 bool isSigned) { 2817 EVT VT = N->getValueType(0); 2818 2819 if (N->getOpcode() != ISD::BUILD_VECTOR) 2820 return false; 2821 2822 for (const SDValue &Elt : N->op_values()) { 2823 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 2824 unsigned EltSize = VT.getScalarSizeInBits(); 2825 unsigned HalfSize = EltSize / 2; 2826 if (isSigned) { 2827 if (!isIntN(HalfSize, C->getSExtValue())) 2828 return false; 2829 } else { 2830 if (!isUIntN(HalfSize, C->getZExtValue())) 2831 return false; 2832 } 2833 continue; 2834 } 2835 return false; 2836 } 2837 2838 return true; 2839 } 2840 2841 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) { 2842 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 2843 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG, 2844 N->getOperand(0)->getValueType(0), 2845 N->getValueType(0), 2846 N->getOpcode()); 2847 2848 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 2849 EVT VT = N->getValueType(0); 2850 SDLoc dl(N); 2851 unsigned EltSize = VT.getScalarSizeInBits() / 2; 2852 unsigned NumElts = VT.getVectorNumElements(); 2853 MVT TruncVT = MVT::getIntegerVT(EltSize); 2854 SmallVector<SDValue, 8> Ops; 2855 for (unsigned i = 0; i != NumElts; ++i) { 2856 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 2857 const APInt &CInt = C->getAPIntValue(); 2858 // Element types smaller than 32 bits are not legal, so use i32 elements. 2859 // The values are implicitly truncated so sext vs. zext doesn't matter. 2860 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 2861 } 2862 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 2863 } 2864 2865 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 2866 return N->getOpcode() == ISD::SIGN_EXTEND || 2867 isExtendedBUILD_VECTOR(N, DAG, true); 2868 } 2869 2870 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 2871 return N->getOpcode() == ISD::ZERO_EXTEND || 2872 isExtendedBUILD_VECTOR(N, DAG, false); 2873 } 2874 2875 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 2876 unsigned Opcode = N->getOpcode(); 2877 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 2878 SDNode *N0 = N->getOperand(0).getNode(); 2879 SDNode *N1 = N->getOperand(1).getNode(); 2880 return N0->hasOneUse() && N1->hasOneUse() && 2881 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 2882 } 2883 return false; 2884 } 2885 2886 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 2887 unsigned Opcode = N->getOpcode(); 2888 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 2889 SDNode *N0 = N->getOperand(0).getNode(); 2890 SDNode *N1 = N->getOperand(1).getNode(); 2891 return N0->hasOneUse() && N1->hasOneUse() && 2892 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 2893 } 2894 return false; 2895 } 2896 2897 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op, 2898 SelectionDAG &DAG) const { 2899 // The rounding mode is in bits 23:22 of the FPSCR. 2900 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 2901 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 2902 // so that the shift + and get folded into a bitfield extract. 2903 SDLoc dl(Op); 2904 2905 SDValue Chain = Op.getOperand(0); 2906 SDValue FPCR_64 = DAG.getNode( 2907 ISD::INTRINSIC_W_CHAIN, dl, {MVT::i64, MVT::Other}, 2908 {Chain, DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl, MVT::i64)}); 2909 Chain = FPCR_64.getValue(1); 2910 SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64); 2911 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32, 2912 DAG.getConstant(1U << 22, dl, MVT::i32)); 2913 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 2914 DAG.getConstant(22, dl, MVT::i32)); 2915 SDValue AND = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 2916 DAG.getConstant(3, dl, MVT::i32)); 2917 return DAG.getMergeValues({AND, Chain}, dl); 2918 } 2919 2920 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 2921 // Multiplications are only custom-lowered for 128-bit vectors so that 2922 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 2923 EVT VT = Op.getValueType(); 2924 assert(VT.is128BitVector() && VT.isInteger() && 2925 "unexpected type for custom-lowering ISD::MUL"); 2926 SDNode *N0 = Op.getOperand(0).getNode(); 2927 SDNode *N1 = Op.getOperand(1).getNode(); 2928 unsigned NewOpc = 0; 2929 bool isMLA = false; 2930 bool isN0SExt = isSignExtended(N0, DAG); 2931 bool isN1SExt = isSignExtended(N1, DAG); 2932 if (isN0SExt && isN1SExt) 2933 NewOpc = AArch64ISD::SMULL; 2934 else { 2935 bool isN0ZExt = isZeroExtended(N0, DAG); 2936 bool isN1ZExt = isZeroExtended(N1, DAG); 2937 if (isN0ZExt && isN1ZExt) 2938 NewOpc = AArch64ISD::UMULL; 2939 else if (isN1SExt || isN1ZExt) { 2940 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 2941 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 2942 if (isN1SExt && isAddSubSExt(N0, DAG)) { 2943 NewOpc = AArch64ISD::SMULL; 2944 isMLA = true; 2945 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 2946 NewOpc = AArch64ISD::UMULL; 2947 isMLA = true; 2948 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 2949 std::swap(N0, N1); 2950 NewOpc = AArch64ISD::UMULL; 2951 isMLA = true; 2952 } 2953 } 2954 2955 if (!NewOpc) { 2956 if (VT == MVT::v2i64) 2957 // Fall through to expand this. It is not legal. 2958 return SDValue(); 2959 else 2960 // Other vector multiplications are legal. 2961 return Op; 2962 } 2963 } 2964 2965 // Legalize to a S/UMULL instruction 2966 SDLoc DL(Op); 2967 SDValue Op0; 2968 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG); 2969 if (!isMLA) { 2970 Op0 = skipExtensionForVectorMULL(N0, DAG); 2971 assert(Op0.getValueType().is64BitVector() && 2972 Op1.getValueType().is64BitVector() && 2973 "unexpected types for extended operands to VMULL"); 2974 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 2975 } 2976 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during 2977 // isel lowering to take advantage of no-stall back to back s/umul + s/umla. 2978 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57 2979 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG); 2980 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG); 2981 EVT Op1VT = Op1.getValueType(); 2982 return DAG.getNode(N0->getOpcode(), DL, VT, 2983 DAG.getNode(NewOpc, DL, VT, 2984 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 2985 DAG.getNode(NewOpc, DL, VT, 2986 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 2987 } 2988 2989 static inline SDValue getPTrue(SelectionDAG &DAG, SDLoc DL, EVT VT, 2990 int Pattern) { 2991 return DAG.getNode(AArch64ISD::PTRUE, DL, VT, 2992 DAG.getTargetConstant(Pattern, DL, MVT::i32)); 2993 } 2994 2995 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 2996 SelectionDAG &DAG) const { 2997 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2998 SDLoc dl(Op); 2999 switch (IntNo) { 3000 default: return SDValue(); // Don't custom lower most intrinsics. 3001 case Intrinsic::thread_pointer: { 3002 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3003 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT); 3004 } 3005 case Intrinsic::aarch64_neon_abs: { 3006 EVT Ty = Op.getValueType(); 3007 if (Ty == MVT::i64) { 3008 SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, 3009 Op.getOperand(1)); 3010 Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result); 3011 return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result); 3012 } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) { 3013 return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1)); 3014 } else { 3015 report_fatal_error("Unexpected type for AArch64 NEON intrinic"); 3016 } 3017 } 3018 case Intrinsic::aarch64_neon_smax: 3019 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(), 3020 Op.getOperand(1), Op.getOperand(2)); 3021 case Intrinsic::aarch64_neon_umax: 3022 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(), 3023 Op.getOperand(1), Op.getOperand(2)); 3024 case Intrinsic::aarch64_neon_smin: 3025 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(), 3026 Op.getOperand(1), Op.getOperand(2)); 3027 case Intrinsic::aarch64_neon_umin: 3028 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(), 3029 Op.getOperand(1), Op.getOperand(2)); 3030 3031 case Intrinsic::aarch64_sve_sunpkhi: 3032 return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(), 3033 Op.getOperand(1)); 3034 case Intrinsic::aarch64_sve_sunpklo: 3035 return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(), 3036 Op.getOperand(1)); 3037 case Intrinsic::aarch64_sve_uunpkhi: 3038 return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(), 3039 Op.getOperand(1)); 3040 case Intrinsic::aarch64_sve_uunpklo: 3041 return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(), 3042 Op.getOperand(1)); 3043 case Intrinsic::aarch64_sve_clasta_n: 3044 return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(), 3045 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3046 case Intrinsic::aarch64_sve_clastb_n: 3047 return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(), 3048 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 3049 case Intrinsic::aarch64_sve_lasta: 3050 return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(), 3051 Op.getOperand(1), Op.getOperand(2)); 3052 case Intrinsic::aarch64_sve_lastb: 3053 return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(), 3054 Op.getOperand(1), Op.getOperand(2)); 3055 case Intrinsic::aarch64_sve_rev: 3056 return DAG.getNode(AArch64ISD::REV, dl, Op.getValueType(), 3057 Op.getOperand(1)); 3058 case Intrinsic::aarch64_sve_tbl: 3059 return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(), 3060 Op.getOperand(1), Op.getOperand(2)); 3061 case Intrinsic::aarch64_sve_trn1: 3062 return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(), 3063 Op.getOperand(1), Op.getOperand(2)); 3064 case Intrinsic::aarch64_sve_trn2: 3065 return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(), 3066 Op.getOperand(1), Op.getOperand(2)); 3067 case Intrinsic::aarch64_sve_uzp1: 3068 return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(), 3069 Op.getOperand(1), Op.getOperand(2)); 3070 case Intrinsic::aarch64_sve_uzp2: 3071 return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(), 3072 Op.getOperand(1), Op.getOperand(2)); 3073 case Intrinsic::aarch64_sve_zip1: 3074 return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(), 3075 Op.getOperand(1), Op.getOperand(2)); 3076 case Intrinsic::aarch64_sve_zip2: 3077 return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(), 3078 Op.getOperand(1), Op.getOperand(2)); 3079 case Intrinsic::aarch64_sve_ptrue: 3080 return DAG.getNode(AArch64ISD::PTRUE, dl, Op.getValueType(), 3081 Op.getOperand(1)); 3082 case Intrinsic::aarch64_sve_dupq_lane: 3083 return LowerDUPQLane(Op, DAG); 3084 case Intrinsic::aarch64_sve_convert_from_svbool: 3085 return DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, Op.getValueType(), 3086 Op.getOperand(1)); 3087 case Intrinsic::aarch64_sve_convert_to_svbool: { 3088 EVT OutVT = Op.getValueType(); 3089 EVT InVT = Op.getOperand(1).getValueType(); 3090 // Return the operand if the cast isn't changing type, 3091 // i.e. <n x 16 x i1> -> <n x 16 x i1> 3092 if (InVT == OutVT) 3093 return Op.getOperand(1); 3094 // Otherwise, zero the newly introduced lanes. 3095 SDValue Reinterpret = 3096 DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Op.getOperand(1)); 3097 SDValue Mask = getPTrue(DAG, dl, InVT, AArch64SVEPredPattern::all); 3098 SDValue MaskReinterpret = 3099 DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Mask); 3100 return DAG.getNode(ISD::AND, dl, OutVT, Reinterpret, MaskReinterpret); 3101 } 3102 3103 case Intrinsic::aarch64_sve_insr: { 3104 SDValue Scalar = Op.getOperand(2); 3105 EVT ScalarTy = Scalar.getValueType(); 3106 if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) 3107 Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar); 3108 3109 return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(), 3110 Op.getOperand(1), Scalar); 3111 } 3112 3113 case Intrinsic::localaddress: { 3114 const auto &MF = DAG.getMachineFunction(); 3115 const auto *RegInfo = Subtarget->getRegisterInfo(); 3116 unsigned Reg = RegInfo->getLocalAddressRegister(MF); 3117 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, 3118 Op.getSimpleValueType()); 3119 } 3120 3121 case Intrinsic::eh_recoverfp: { 3122 // FIXME: This needs to be implemented to correctly handle highly aligned 3123 // stack objects. For now we simply return the incoming FP. Refer D53541 3124 // for more details. 3125 SDValue FnOp = Op.getOperand(1); 3126 SDValue IncomingFPOp = Op.getOperand(2); 3127 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp); 3128 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr); 3129 if (!Fn) 3130 report_fatal_error( 3131 "llvm.eh.recoverfp must take a function as the first argument"); 3132 return IncomingFPOp; 3133 } 3134 } 3135 } 3136 3137 bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const { 3138 return ExtVal.getValueType().isScalableVector(); 3139 } 3140 3141 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16. 3142 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST, 3143 EVT VT, EVT MemVT, 3144 SelectionDAG &DAG) { 3145 assert(VT.isVector() && "VT should be a vector type"); 3146 assert(MemVT == MVT::v4i8 && VT == MVT::v4i16); 3147 3148 SDValue Value = ST->getValue(); 3149 3150 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract 3151 // the word lane which represent the v4i8 subvector. It optimizes the store 3152 // to: 3153 // 3154 // xtn v0.8b, v0.8h 3155 // str s0, [x0] 3156 3157 SDValue Undef = DAG.getUNDEF(MVT::i16); 3158 SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL, 3159 {Undef, Undef, Undef, Undef}); 3160 3161 SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16, 3162 Value, UndefVec); 3163 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt); 3164 3165 Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc); 3166 SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 3167 Trunc, DAG.getConstant(0, DL, MVT::i64)); 3168 3169 return DAG.getStore(ST->getChain(), DL, ExtractTrunc, 3170 ST->getBasePtr(), ST->getMemOperand()); 3171 } 3172 3173 // Custom lowering for any store, vector or scalar and/or default or with 3174 // a truncate operations. Currently only custom lower truncate operation 3175 // from vector v4i16 to v4i8 or volatile stores of i128. 3176 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op, 3177 SelectionDAG &DAG) const { 3178 SDLoc Dl(Op); 3179 StoreSDNode *StoreNode = cast<StoreSDNode>(Op); 3180 assert (StoreNode && "Can only custom lower store nodes"); 3181 3182 SDValue Value = StoreNode->getValue(); 3183 3184 EVT VT = Value.getValueType(); 3185 EVT MemVT = StoreNode->getMemoryVT(); 3186 3187 if (VT.isVector()) { 3188 unsigned AS = StoreNode->getAddressSpace(); 3189 unsigned Align = StoreNode->getAlignment(); 3190 if (Align < MemVT.getStoreSize() && 3191 !allowsMisalignedMemoryAccesses(MemVT, AS, Align, 3192 StoreNode->getMemOperand()->getFlags(), 3193 nullptr)) { 3194 return scalarizeVectorStore(StoreNode, DAG); 3195 } 3196 3197 if (StoreNode->isTruncatingStore()) { 3198 return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG); 3199 } 3200 // 256 bit non-temporal stores can be lowered to STNP. Do this as part of 3201 // the custom lowering, as there are no un-paired non-temporal stores and 3202 // legalization will break up 256 bit inputs. 3203 if (StoreNode->isNonTemporal() && MemVT.getSizeInBits() == 256u && 3204 MemVT.getVectorElementCount().Min % 2u == 0 && 3205 ((MemVT.getScalarSizeInBits() == 8u || 3206 MemVT.getScalarSizeInBits() == 16u || 3207 MemVT.getScalarSizeInBits() == 32u || 3208 MemVT.getScalarSizeInBits() == 64u))) { 3209 SDValue Lo = 3210 DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl, 3211 MemVT.getHalfNumVectorElementsVT(*DAG.getContext()), 3212 StoreNode->getValue(), DAG.getConstant(0, Dl, MVT::i64)); 3213 SDValue Hi = DAG.getNode( 3214 ISD::EXTRACT_SUBVECTOR, Dl, 3215 MemVT.getHalfNumVectorElementsVT(*DAG.getContext()), 3216 StoreNode->getValue(), 3217 DAG.getConstant(MemVT.getVectorElementCount().Min / 2, Dl, MVT::i64)); 3218 SDValue Result = DAG.getMemIntrinsicNode( 3219 AArch64ISD::STNP, Dl, DAG.getVTList(MVT::Other), 3220 {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()}, 3221 StoreNode->getMemoryVT(), StoreNode->getMemOperand()); 3222 return Result; 3223 } 3224 } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) { 3225 assert(StoreNode->getValue()->getValueType(0) == MVT::i128); 3226 SDValue Lo = 3227 DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(), 3228 DAG.getConstant(0, Dl, MVT::i64)); 3229 SDValue Hi = 3230 DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(), 3231 DAG.getConstant(1, Dl, MVT::i64)); 3232 SDValue Result = DAG.getMemIntrinsicNode( 3233 AArch64ISD::STP, Dl, DAG.getVTList(MVT::Other), 3234 {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()}, 3235 StoreNode->getMemoryVT(), StoreNode->getMemOperand()); 3236 return Result; 3237 } 3238 3239 return SDValue(); 3240 } 3241 3242 SDValue AArch64TargetLowering::LowerOperation(SDValue Op, 3243 SelectionDAG &DAG) const { 3244 LLVM_DEBUG(dbgs() << "Custom lowering: "); 3245 LLVM_DEBUG(Op.dump()); 3246 3247 switch (Op.getOpcode()) { 3248 default: 3249 llvm_unreachable("unimplemented operand"); 3250 return SDValue(); 3251 case ISD::BITCAST: 3252 return LowerBITCAST(Op, DAG); 3253 case ISD::GlobalAddress: 3254 return LowerGlobalAddress(Op, DAG); 3255 case ISD::GlobalTLSAddress: 3256 return LowerGlobalTLSAddress(Op, DAG); 3257 case ISD::SETCC: 3258 case ISD::STRICT_FSETCC: 3259 case ISD::STRICT_FSETCCS: 3260 return LowerSETCC(Op, DAG); 3261 case ISD::BR_CC: 3262 return LowerBR_CC(Op, DAG); 3263 case ISD::SELECT: 3264 return LowerSELECT(Op, DAG); 3265 case ISD::SELECT_CC: 3266 return LowerSELECT_CC(Op, DAG); 3267 case ISD::JumpTable: 3268 return LowerJumpTable(Op, DAG); 3269 case ISD::BR_JT: 3270 return LowerBR_JT(Op, DAG); 3271 case ISD::ConstantPool: 3272 return LowerConstantPool(Op, DAG); 3273 case ISD::BlockAddress: 3274 return LowerBlockAddress(Op, DAG); 3275 case ISD::VASTART: 3276 return LowerVASTART(Op, DAG); 3277 case ISD::VACOPY: 3278 return LowerVACOPY(Op, DAG); 3279 case ISD::VAARG: 3280 return LowerVAARG(Op, DAG); 3281 case ISD::ADDC: 3282 case ISD::ADDE: 3283 case ISD::SUBC: 3284 case ISD::SUBE: 3285 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 3286 case ISD::SADDO: 3287 case ISD::UADDO: 3288 case ISD::SSUBO: 3289 case ISD::USUBO: 3290 case ISD::SMULO: 3291 case ISD::UMULO: 3292 return LowerXALUO(Op, DAG); 3293 case ISD::FADD: 3294 return LowerF128Call(Op, DAG, RTLIB::ADD_F128); 3295 case ISD::FSUB: 3296 return LowerF128Call(Op, DAG, RTLIB::SUB_F128); 3297 case ISD::FMUL: 3298 return LowerF128Call(Op, DAG, RTLIB::MUL_F128); 3299 case ISD::FDIV: 3300 return LowerF128Call(Op, DAG, RTLIB::DIV_F128); 3301 case ISD::FP_ROUND: 3302 case ISD::STRICT_FP_ROUND: 3303 return LowerFP_ROUND(Op, DAG); 3304 case ISD::FP_EXTEND: 3305 return LowerFP_EXTEND(Op, DAG); 3306 case ISD::FRAMEADDR: 3307 return LowerFRAMEADDR(Op, DAG); 3308 case ISD::SPONENTRY: 3309 return LowerSPONENTRY(Op, DAG); 3310 case ISD::RETURNADDR: 3311 return LowerRETURNADDR(Op, DAG); 3312 case ISD::ADDROFRETURNADDR: 3313 return LowerADDROFRETURNADDR(Op, DAG); 3314 case ISD::INSERT_VECTOR_ELT: 3315 return LowerINSERT_VECTOR_ELT(Op, DAG); 3316 case ISD::EXTRACT_VECTOR_ELT: 3317 return LowerEXTRACT_VECTOR_ELT(Op, DAG); 3318 case ISD::BUILD_VECTOR: 3319 return LowerBUILD_VECTOR(Op, DAG); 3320 case ISD::VECTOR_SHUFFLE: 3321 return LowerVECTOR_SHUFFLE(Op, DAG); 3322 case ISD::SPLAT_VECTOR: 3323 return LowerSPLAT_VECTOR(Op, DAG); 3324 case ISD::EXTRACT_SUBVECTOR: 3325 return LowerEXTRACT_SUBVECTOR(Op, DAG); 3326 case ISD::SRA: 3327 case ISD::SRL: 3328 case ISD::SHL: 3329 return LowerVectorSRA_SRL_SHL(Op, DAG); 3330 case ISD::SHL_PARTS: 3331 return LowerShiftLeftParts(Op, DAG); 3332 case ISD::SRL_PARTS: 3333 case ISD::SRA_PARTS: 3334 return LowerShiftRightParts(Op, DAG); 3335 case ISD::CTPOP: 3336 return LowerCTPOP(Op, DAG); 3337 case ISD::FCOPYSIGN: 3338 return LowerFCOPYSIGN(Op, DAG); 3339 case ISD::OR: 3340 return LowerVectorOR(Op, DAG); 3341 case ISD::XOR: 3342 return LowerXOR(Op, DAG); 3343 case ISD::PREFETCH: 3344 return LowerPREFETCH(Op, DAG); 3345 case ISD::SINT_TO_FP: 3346 case ISD::UINT_TO_FP: 3347 case ISD::STRICT_SINT_TO_FP: 3348 case ISD::STRICT_UINT_TO_FP: 3349 return LowerINT_TO_FP(Op, DAG); 3350 case ISD::FP_TO_SINT: 3351 case ISD::FP_TO_UINT: 3352 case ISD::STRICT_FP_TO_SINT: 3353 case ISD::STRICT_FP_TO_UINT: 3354 return LowerFP_TO_INT(Op, DAG); 3355 case ISD::FSINCOS: 3356 return LowerFSINCOS(Op, DAG); 3357 case ISD::FLT_ROUNDS_: 3358 return LowerFLT_ROUNDS_(Op, DAG); 3359 case ISD::MUL: 3360 return LowerMUL(Op, DAG); 3361 case ISD::INTRINSIC_WO_CHAIN: 3362 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3363 case ISD::STORE: 3364 return LowerSTORE(Op, DAG); 3365 case ISD::VECREDUCE_ADD: 3366 case ISD::VECREDUCE_SMAX: 3367 case ISD::VECREDUCE_SMIN: 3368 case ISD::VECREDUCE_UMAX: 3369 case ISD::VECREDUCE_UMIN: 3370 case ISD::VECREDUCE_FMAX: 3371 case ISD::VECREDUCE_FMIN: 3372 return LowerVECREDUCE(Op, DAG); 3373 case ISD::ATOMIC_LOAD_SUB: 3374 return LowerATOMIC_LOAD_SUB(Op, DAG); 3375 case ISD::ATOMIC_LOAD_AND: 3376 return LowerATOMIC_LOAD_AND(Op, DAG); 3377 case ISD::DYNAMIC_STACKALLOC: 3378 return LowerDYNAMIC_STACKALLOC(Op, DAG); 3379 case ISD::VSCALE: 3380 return LowerVSCALE(Op, DAG); 3381 } 3382 } 3383 3384 //===----------------------------------------------------------------------===// 3385 // Calling Convention Implementation 3386 //===----------------------------------------------------------------------===// 3387 3388 /// Selects the correct CCAssignFn for a given CallingConvention value. 3389 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC, 3390 bool IsVarArg) const { 3391 switch (CC) { 3392 default: 3393 report_fatal_error("Unsupported calling convention."); 3394 case CallingConv::WebKit_JS: 3395 return CC_AArch64_WebKit_JS; 3396 case CallingConv::GHC: 3397 return CC_AArch64_GHC; 3398 case CallingConv::C: 3399 case CallingConv::Fast: 3400 case CallingConv::PreserveMost: 3401 case CallingConv::CXX_FAST_TLS: 3402 case CallingConv::Swift: 3403 if (Subtarget->isTargetWindows() && IsVarArg) 3404 return CC_AArch64_Win64_VarArg; 3405 if (!Subtarget->isTargetDarwin()) 3406 return CC_AArch64_AAPCS; 3407 if (!IsVarArg) 3408 return CC_AArch64_DarwinPCS; 3409 return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg 3410 : CC_AArch64_DarwinPCS_VarArg; 3411 case CallingConv::Win64: 3412 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS; 3413 case CallingConv::CFGuard_Check: 3414 return CC_AArch64_Win64_CFGuard_Check; 3415 case CallingConv::AArch64_VectorCall: 3416 case CallingConv::AArch64_SVE_VectorCall: 3417 return CC_AArch64_AAPCS; 3418 } 3419 } 3420 3421 CCAssignFn * 3422 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const { 3423 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS 3424 : RetCC_AArch64_AAPCS; 3425 } 3426 3427 SDValue AArch64TargetLowering::LowerFormalArguments( 3428 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3429 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 3430 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3431 MachineFunction &MF = DAG.getMachineFunction(); 3432 MachineFrameInfo &MFI = MF.getFrameInfo(); 3433 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()); 3434 3435 // Assign locations to all of the incoming arguments. 3436 SmallVector<CCValAssign, 16> ArgLocs; 3437 DenseMap<unsigned, SDValue> CopiedRegs; 3438 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3439 *DAG.getContext()); 3440 3441 // At this point, Ins[].VT may already be promoted to i32. To correctly 3442 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 3443 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 3444 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here 3445 // we use a special version of AnalyzeFormalArguments to pass in ValVT and 3446 // LocVT. 3447 unsigned NumArgs = Ins.size(); 3448 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 3449 unsigned CurArgIdx = 0; 3450 for (unsigned i = 0; i != NumArgs; ++i) { 3451 MVT ValVT = Ins[i].VT; 3452 if (Ins[i].isOrigArg()) { 3453 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx); 3454 CurArgIdx = Ins[i].getOrigArgIndex(); 3455 3456 // Get type of the original argument. 3457 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(), 3458 /*AllowUnknown*/ true); 3459 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other; 3460 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 3461 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 3462 ValVT = MVT::i8; 3463 else if (ActualMVT == MVT::i16) 3464 ValVT = MVT::i16; 3465 } 3466 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 3467 bool Res = 3468 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo); 3469 assert(!Res && "Call operand has unhandled type"); 3470 (void)Res; 3471 } 3472 assert(ArgLocs.size() == Ins.size()); 3473 SmallVector<SDValue, 16> ArgValues; 3474 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3475 CCValAssign &VA = ArgLocs[i]; 3476 3477 if (Ins[i].Flags.isByVal()) { 3478 // Byval is used for HFAs in the PCS, but the system should work in a 3479 // non-compliant manner for larger structs. 3480 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3481 int Size = Ins[i].Flags.getByValSize(); 3482 unsigned NumRegs = (Size + 7) / 8; 3483 3484 // FIXME: This works on big-endian for composite byvals, which are the common 3485 // case. It should also work for fundamental types too. 3486 unsigned FrameIdx = 3487 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false); 3488 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT); 3489 InVals.push_back(FrameIdxN); 3490 3491 continue; 3492 } 3493 3494 SDValue ArgValue; 3495 if (VA.isRegLoc()) { 3496 // Arguments stored in registers. 3497 EVT RegVT = VA.getLocVT(); 3498 const TargetRegisterClass *RC; 3499 3500 if (RegVT == MVT::i32) 3501 RC = &AArch64::GPR32RegClass; 3502 else if (RegVT == MVT::i64) 3503 RC = &AArch64::GPR64RegClass; 3504 else if (RegVT == MVT::f16) 3505 RC = &AArch64::FPR16RegClass; 3506 else if (RegVT == MVT::f32) 3507 RC = &AArch64::FPR32RegClass; 3508 else if (RegVT == MVT::f64 || RegVT.is64BitVector()) 3509 RC = &AArch64::FPR64RegClass; 3510 else if (RegVT == MVT::f128 || RegVT.is128BitVector()) 3511 RC = &AArch64::FPR128RegClass; 3512 else if (RegVT.isScalableVector() && 3513 RegVT.getVectorElementType() == MVT::i1) 3514 RC = &AArch64::PPRRegClass; 3515 else if (RegVT.isScalableVector()) 3516 RC = &AArch64::ZPRRegClass; 3517 else 3518 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3519 3520 // Transform the arguments in physical registers into virtual ones. 3521 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3522 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT); 3523 3524 // If this is an 8, 16 or 32-bit value, it is really passed promoted 3525 // to 64 bits. Insert an assert[sz]ext to capture this, then 3526 // truncate to the right size. 3527 switch (VA.getLocInfo()) { 3528 default: 3529 llvm_unreachable("Unknown loc info!"); 3530 case CCValAssign::Full: 3531 break; 3532 case CCValAssign::Indirect: 3533 assert(VA.getValVT().isScalableVector() && 3534 "Only scalable vectors can be passed indirectly"); 3535 break; 3536 case CCValAssign::BCvt: 3537 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue); 3538 break; 3539 case CCValAssign::AExt: 3540 case CCValAssign::SExt: 3541 case CCValAssign::ZExt: 3542 break; 3543 case CCValAssign::AExtUpper: 3544 ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue, 3545 DAG.getConstant(32, DL, RegVT)); 3546 ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT()); 3547 break; 3548 } 3549 } else { // VA.isRegLoc() 3550 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem"); 3551 unsigned ArgOffset = VA.getLocMemOffset(); 3552 unsigned ArgSize = (VA.getLocInfo() == CCValAssign::Indirect 3553 ? VA.getLocVT().getSizeInBits() 3554 : VA.getValVT().getSizeInBits()) / 8; 3555 3556 uint32_t BEAlign = 0; 3557 if (!Subtarget->isLittleEndian() && ArgSize < 8 && 3558 !Ins[i].Flags.isInConsecutiveRegs()) 3559 BEAlign = 8 - ArgSize; 3560 3561 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true); 3562 3563 // Create load nodes to retrieve arguments from the stack. 3564 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3565 3566 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 3567 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 3568 MVT MemVT = VA.getValVT(); 3569 3570 switch (VA.getLocInfo()) { 3571 default: 3572 break; 3573 case CCValAssign::Trunc: 3574 case CCValAssign::BCvt: 3575 MemVT = VA.getLocVT(); 3576 break; 3577 case CCValAssign::Indirect: 3578 assert(VA.getValVT().isScalableVector() && 3579 "Only scalable vectors can be passed indirectly"); 3580 MemVT = VA.getLocVT(); 3581 break; 3582 case CCValAssign::SExt: 3583 ExtType = ISD::SEXTLOAD; 3584 break; 3585 case CCValAssign::ZExt: 3586 ExtType = ISD::ZEXTLOAD; 3587 break; 3588 case CCValAssign::AExt: 3589 ExtType = ISD::EXTLOAD; 3590 break; 3591 } 3592 3593 ArgValue = DAG.getExtLoad( 3594 ExtType, DL, VA.getLocVT(), Chain, FIN, 3595 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 3596 MemVT); 3597 3598 } 3599 3600 if (VA.getLocInfo() == CCValAssign::Indirect) { 3601 assert(VA.getValVT().isScalableVector() && 3602 "Only scalable vectors can be passed indirectly"); 3603 // If value is passed via pointer - do a load. 3604 ArgValue = 3605 DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, MachinePointerInfo()); 3606 } 3607 3608 if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer()) 3609 ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(), 3610 ArgValue, DAG.getValueType(MVT::i32)); 3611 InVals.push_back(ArgValue); 3612 } 3613 3614 // varargs 3615 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 3616 if (isVarArg) { 3617 if (!Subtarget->isTargetDarwin() || IsWin64) { 3618 // The AAPCS variadic function ABI is identical to the non-variadic 3619 // one. As a result there may be more arguments in registers and we should 3620 // save them for future reference. 3621 // Win64 variadic functions also pass arguments in registers, but all float 3622 // arguments are passed in integer registers. 3623 saveVarArgRegisters(CCInfo, DAG, DL, Chain); 3624 } 3625 3626 // This will point to the next argument passed via stack. 3627 unsigned StackOffset = CCInfo.getNextStackOffset(); 3628 // We currently pass all varargs at 8-byte alignment, or 4 for ILP32 3629 StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8); 3630 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true)); 3631 3632 if (MFI.hasMustTailInVarArgFunc()) { 3633 SmallVector<MVT, 2> RegParmTypes; 3634 RegParmTypes.push_back(MVT::i64); 3635 RegParmTypes.push_back(MVT::f128); 3636 // Compute the set of forwarded registers. The rest are scratch. 3637 SmallVectorImpl<ForwardedRegister> &Forwards = 3638 FuncInfo->getForwardedMustTailRegParms(); 3639 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, 3640 CC_AArch64_AAPCS); 3641 3642 // Conservatively forward X8, since it might be used for aggregate return. 3643 if (!CCInfo.isAllocated(AArch64::X8)) { 3644 unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass); 3645 Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64)); 3646 } 3647 } 3648 } 3649 3650 // On Windows, InReg pointers must be returned, so record the pointer in a 3651 // virtual register at the start of the function so it can be returned in the 3652 // epilogue. 3653 if (IsWin64) { 3654 for (unsigned I = 0, E = Ins.size(); I != E; ++I) { 3655 if (Ins[I].Flags.isInReg()) { 3656 assert(!FuncInfo->getSRetReturnReg()); 3657 3658 MVT PtrTy = getPointerTy(DAG.getDataLayout()); 3659 Register Reg = 3660 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy)); 3661 FuncInfo->setSRetReturnReg(Reg); 3662 3663 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]); 3664 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain); 3665 break; 3666 } 3667 } 3668 } 3669 3670 unsigned StackArgSize = CCInfo.getNextStackOffset(); 3671 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3672 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) { 3673 // This is a non-standard ABI so by fiat I say we're allowed to make full 3674 // use of the stack area to be popped, which must be aligned to 16 bytes in 3675 // any case: 3676 StackArgSize = alignTo(StackArgSize, 16); 3677 3678 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding 3679 // a multiple of 16. 3680 FuncInfo->setArgumentStackToRestore(StackArgSize); 3681 3682 // This realignment carries over to the available bytes below. Our own 3683 // callers will guarantee the space is free by giving an aligned value to 3684 // CALLSEQ_START. 3685 } 3686 // Even if we're not expected to free up the space, it's useful to know how 3687 // much is there while considering tail calls (because we can reuse it). 3688 FuncInfo->setBytesInStackArgArea(StackArgSize); 3689 3690 if (Subtarget->hasCustomCallingConv()) 3691 Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF); 3692 3693 return Chain; 3694 } 3695 3696 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo, 3697 SelectionDAG &DAG, 3698 const SDLoc &DL, 3699 SDValue &Chain) const { 3700 MachineFunction &MF = DAG.getMachineFunction(); 3701 MachineFrameInfo &MFI = MF.getFrameInfo(); 3702 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 3703 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3704 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()); 3705 3706 SmallVector<SDValue, 8> MemOps; 3707 3708 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2, 3709 AArch64::X3, AArch64::X4, AArch64::X5, 3710 AArch64::X6, AArch64::X7 }; 3711 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs); 3712 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs); 3713 3714 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR); 3715 int GPRIdx = 0; 3716 if (GPRSaveSize != 0) { 3717 if (IsWin64) { 3718 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false); 3719 if (GPRSaveSize & 15) 3720 // The extra size here, if triggered, will always be 8. 3721 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false); 3722 } else 3723 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false); 3724 3725 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT); 3726 3727 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) { 3728 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass); 3729 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64); 3730 SDValue Store = DAG.getStore( 3731 Val.getValue(1), DL, Val, FIN, 3732 IsWin64 3733 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 3734 GPRIdx, 3735 (i - FirstVariadicGPR) * 8) 3736 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8)); 3737 MemOps.push_back(Store); 3738 FIN = 3739 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT)); 3740 } 3741 } 3742 FuncInfo->setVarArgsGPRIndex(GPRIdx); 3743 FuncInfo->setVarArgsGPRSize(GPRSaveSize); 3744 3745 if (Subtarget->hasFPARMv8() && !IsWin64) { 3746 static const MCPhysReg FPRArgRegs[] = { 3747 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, 3748 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7}; 3749 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs); 3750 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs); 3751 3752 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR); 3753 int FPRIdx = 0; 3754 if (FPRSaveSize != 0) { 3755 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false); 3756 3757 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT); 3758 3759 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) { 3760 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass); 3761 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128); 3762 3763 SDValue Store = DAG.getStore( 3764 Val.getValue(1), DL, Val, FIN, 3765 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16)); 3766 MemOps.push_back(Store); 3767 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, 3768 DAG.getConstant(16, DL, PtrVT)); 3769 } 3770 } 3771 FuncInfo->setVarArgsFPRIndex(FPRIdx); 3772 FuncInfo->setVarArgsFPRSize(FPRSaveSize); 3773 } 3774 3775 if (!MemOps.empty()) { 3776 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 3777 } 3778 } 3779 3780 /// LowerCallResult - Lower the result values of a call into the 3781 /// appropriate copies out of appropriate physical registers. 3782 SDValue AArch64TargetLowering::LowerCallResult( 3783 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 3784 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 3785 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 3786 SDValue ThisVal) const { 3787 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 3788 ? RetCC_AArch64_WebKit_JS 3789 : RetCC_AArch64_AAPCS; 3790 // Assign locations to each value returned by this call. 3791 SmallVector<CCValAssign, 16> RVLocs; 3792 DenseMap<unsigned, SDValue> CopiedRegs; 3793 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 3794 *DAG.getContext()); 3795 CCInfo.AnalyzeCallResult(Ins, RetCC); 3796 3797 // Copy all of the result registers out of their specified physreg. 3798 for (unsigned i = 0; i != RVLocs.size(); ++i) { 3799 CCValAssign VA = RVLocs[i]; 3800 3801 // Pass 'this' value directly from the argument to return value, to avoid 3802 // reg unit interference 3803 if (i == 0 && isThisReturn) { 3804 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 && 3805 "unexpected return calling convention register assignment"); 3806 InVals.push_back(ThisVal); 3807 continue; 3808 } 3809 3810 // Avoid copying a physreg twice since RegAllocFast is incompetent and only 3811 // allows one use of a physreg per block. 3812 SDValue Val = CopiedRegs.lookup(VA.getLocReg()); 3813 if (!Val) { 3814 Val = 3815 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 3816 Chain = Val.getValue(1); 3817 InFlag = Val.getValue(2); 3818 CopiedRegs[VA.getLocReg()] = Val; 3819 } 3820 3821 switch (VA.getLocInfo()) { 3822 default: 3823 llvm_unreachable("Unknown loc info!"); 3824 case CCValAssign::Full: 3825 break; 3826 case CCValAssign::BCvt: 3827 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 3828 break; 3829 case CCValAssign::AExtUpper: 3830 Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val, 3831 DAG.getConstant(32, DL, VA.getLocVT())); 3832 LLVM_FALLTHROUGH; 3833 case CCValAssign::AExt: 3834 LLVM_FALLTHROUGH; 3835 case CCValAssign::ZExt: 3836 Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT()); 3837 break; 3838 } 3839 3840 InVals.push_back(Val); 3841 } 3842 3843 return Chain; 3844 } 3845 3846 /// Return true if the calling convention is one that we can guarantee TCO for. 3847 static bool canGuaranteeTCO(CallingConv::ID CC) { 3848 return CC == CallingConv::Fast; 3849 } 3850 3851 /// Return true if we might ever do TCO for calls with this calling convention. 3852 static bool mayTailCallThisCC(CallingConv::ID CC) { 3853 switch (CC) { 3854 case CallingConv::C: 3855 case CallingConv::PreserveMost: 3856 case CallingConv::Swift: 3857 return true; 3858 default: 3859 return canGuaranteeTCO(CC); 3860 } 3861 } 3862 3863 bool AArch64TargetLowering::isEligibleForTailCallOptimization( 3864 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 3865 const SmallVectorImpl<ISD::OutputArg> &Outs, 3866 const SmallVectorImpl<SDValue> &OutVals, 3867 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 3868 if (!mayTailCallThisCC(CalleeCC)) 3869 return false; 3870 3871 MachineFunction &MF = DAG.getMachineFunction(); 3872 const Function &CallerF = MF.getFunction(); 3873 CallingConv::ID CallerCC = CallerF.getCallingConv(); 3874 bool CCMatch = CallerCC == CalleeCC; 3875 3876 // Byval parameters hand the function a pointer directly into the stack area 3877 // we want to reuse during a tail call. Working around this *is* possible (see 3878 // X86) but less efficient and uglier in LowerCall. 3879 for (Function::const_arg_iterator i = CallerF.arg_begin(), 3880 e = CallerF.arg_end(); 3881 i != e; ++i) { 3882 if (i->hasByValAttr()) 3883 return false; 3884 3885 // On Windows, "inreg" attributes signify non-aggregate indirect returns. 3886 // In this case, it is necessary to save/restore X0 in the callee. Tail 3887 // call opt interferes with this. So we disable tail call opt when the 3888 // caller has an argument with "inreg" attribute. 3889 3890 // FIXME: Check whether the callee also has an "inreg" argument. 3891 if (i->hasInRegAttr()) 3892 return false; 3893 } 3894 3895 if (getTargetMachine().Options.GuaranteedTailCallOpt) 3896 return canGuaranteeTCO(CalleeCC) && CCMatch; 3897 3898 // Externally-defined functions with weak linkage should not be 3899 // tail-called on AArch64 when the OS does not support dynamic 3900 // pre-emption of symbols, as the AAELF spec requires normal calls 3901 // to undefined weak functions to be replaced with a NOP or jump to the 3902 // next instruction. The behaviour of branch instructions in this 3903 // situation (as used for tail calls) is implementation-defined, so we 3904 // cannot rely on the linker replacing the tail call with a return. 3905 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3906 const GlobalValue *GV = G->getGlobal(); 3907 const Triple &TT = getTargetMachine().getTargetTriple(); 3908 if (GV->hasExternalWeakLinkage() && 3909 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 3910 return false; 3911 } 3912 3913 // Now we search for cases where we can use a tail call without changing the 3914 // ABI. Sibcall is used in some places (particularly gcc) to refer to this 3915 // concept. 3916 3917 // I want anyone implementing a new calling convention to think long and hard 3918 // about this assert. 3919 assert((!isVarArg || CalleeCC == CallingConv::C) && 3920 "Unexpected variadic calling convention"); 3921 3922 LLVMContext &C = *DAG.getContext(); 3923 if (isVarArg && !Outs.empty()) { 3924 // At least two cases here: if caller is fastcc then we can't have any 3925 // memory arguments (we'd be expected to clean up the stack afterwards). If 3926 // caller is C then we could potentially use its argument area. 3927 3928 // FIXME: for now we take the most conservative of these in both cases: 3929 // disallow all variadic memory operands. 3930 SmallVector<CCValAssign, 16> ArgLocs; 3931 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 3932 3933 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true)); 3934 for (const CCValAssign &ArgLoc : ArgLocs) 3935 if (!ArgLoc.isRegLoc()) 3936 return false; 3937 } 3938 3939 // Check that the call results are passed in the same way. 3940 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 3941 CCAssignFnForCall(CalleeCC, isVarArg), 3942 CCAssignFnForCall(CallerCC, isVarArg))) 3943 return false; 3944 // The callee has to preserve all registers the caller needs to preserve. 3945 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 3946 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 3947 if (!CCMatch) { 3948 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 3949 if (Subtarget->hasCustomCallingConv()) { 3950 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved); 3951 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved); 3952 } 3953 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 3954 return false; 3955 } 3956 3957 // Nothing more to check if the callee is taking no arguments 3958 if (Outs.empty()) 3959 return true; 3960 3961 SmallVector<CCValAssign, 16> ArgLocs; 3962 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 3963 3964 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 3965 3966 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 3967 3968 // If any of the arguments is passed indirectly, it must be SVE, so the 3969 // 'getBytesInStackArgArea' is not sufficient to determine whether we need to 3970 // allocate space on the stack. That is why we determine this explicitly here 3971 // the call cannot be a tailcall. 3972 if (llvm::any_of(ArgLocs, [](CCValAssign &A) { 3973 assert((A.getLocInfo() != CCValAssign::Indirect || 3974 A.getValVT().isScalableVector()) && 3975 "Expected value to be scalable"); 3976 return A.getLocInfo() == CCValAssign::Indirect; 3977 })) 3978 return false; 3979 3980 // If the stack arguments for this call do not fit into our own save area then 3981 // the call cannot be made tail. 3982 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 3983 return false; 3984 3985 const MachineRegisterInfo &MRI = MF.getRegInfo(); 3986 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 3987 return false; 3988 3989 return true; 3990 } 3991 3992 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain, 3993 SelectionDAG &DAG, 3994 MachineFrameInfo &MFI, 3995 int ClobberedFI) const { 3996 SmallVector<SDValue, 8> ArgChains; 3997 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI); 3998 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1; 3999 4000 // Include the original chain at the beginning of the list. When this is 4001 // used by target LowerCall hooks, this helps legalize find the 4002 // CALLSEQ_BEGIN node. 4003 ArgChains.push_back(Chain); 4004 4005 // Add a chain value for each stack argument corresponding 4006 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(), 4007 UE = DAG.getEntryNode().getNode()->use_end(); 4008 U != UE; ++U) 4009 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 4010 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 4011 if (FI->getIndex() < 0) { 4012 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex()); 4013 int64_t InLastByte = InFirstByte; 4014 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1; 4015 4016 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) || 4017 (FirstByte <= InFirstByte && InFirstByte <= LastByte)) 4018 ArgChains.push_back(SDValue(L, 1)); 4019 } 4020 4021 // Build a tokenfactor for all the chains. 4022 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 4023 } 4024 4025 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC, 4026 bool TailCallOpt) const { 4027 return CallCC == CallingConv::Fast && TailCallOpt; 4028 } 4029 4030 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain, 4031 /// and add input and output parameter nodes. 4032 SDValue 4033 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI, 4034 SmallVectorImpl<SDValue> &InVals) const { 4035 SelectionDAG &DAG = CLI.DAG; 4036 SDLoc &DL = CLI.DL; 4037 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 4038 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 4039 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 4040 SDValue Chain = CLI.Chain; 4041 SDValue Callee = CLI.Callee; 4042 bool &IsTailCall = CLI.IsTailCall; 4043 CallingConv::ID CallConv = CLI.CallConv; 4044 bool IsVarArg = CLI.IsVarArg; 4045 4046 MachineFunction &MF = DAG.getMachineFunction(); 4047 MachineFunction::CallSiteInfo CSInfo; 4048 bool IsThisReturn = false; 4049 4050 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 4051 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 4052 bool IsSibCall = false; 4053 4054 if (IsTailCall) { 4055 // Check if it's really possible to do a tail call. 4056 IsTailCall = isEligibleForTailCallOptimization( 4057 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 4058 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) 4059 report_fatal_error("failed to perform tail call elimination on a call " 4060 "site marked musttail"); 4061 4062 // A sibling call is one where we're under the usual C ABI and not planning 4063 // to change that but can still do a tail call: 4064 if (!TailCallOpt && IsTailCall) 4065 IsSibCall = true; 4066 4067 if (IsTailCall) 4068 ++NumTailCalls; 4069 } 4070 4071 // Analyze operands of the call, assigning locations to each operand. 4072 SmallVector<CCValAssign, 16> ArgLocs; 4073 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, 4074 *DAG.getContext()); 4075 4076 if (IsVarArg) { 4077 // Handle fixed and variable vector arguments differently. 4078 // Variable vector arguments always go into memory. 4079 unsigned NumArgs = Outs.size(); 4080 4081 for (unsigned i = 0; i != NumArgs; ++i) { 4082 MVT ArgVT = Outs[i].VT; 4083 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 4084 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, 4085 /*IsVarArg=*/ !Outs[i].IsFixed); 4086 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo); 4087 assert(!Res && "Call operand has unhandled type"); 4088 (void)Res; 4089 } 4090 } else { 4091 // At this point, Outs[].VT may already be promoted to i32. To correctly 4092 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 4093 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 4094 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here 4095 // we use a special version of AnalyzeCallOperands to pass in ValVT and 4096 // LocVT. 4097 unsigned NumArgs = Outs.size(); 4098 for (unsigned i = 0; i != NumArgs; ++i) { 4099 MVT ValVT = Outs[i].VT; 4100 // Get type of the original argument. 4101 EVT ActualVT = getValueType(DAG.getDataLayout(), 4102 CLI.getArgs()[Outs[i].OrigArgIndex].Ty, 4103 /*AllowUnknown*/ true); 4104 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT; 4105 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 4106 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 4107 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 4108 ValVT = MVT::i8; 4109 else if (ActualMVT == MVT::i16) 4110 ValVT = MVT::i16; 4111 4112 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 4113 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo); 4114 assert(!Res && "Call operand has unhandled type"); 4115 (void)Res; 4116 } 4117 } 4118 4119 // Get a count of how many bytes are to be pushed on the stack. 4120 unsigned NumBytes = CCInfo.getNextStackOffset(); 4121 4122 if (IsSibCall) { 4123 // Since we're not changing the ABI to make this a tail call, the memory 4124 // operands are already available in the caller's incoming argument space. 4125 NumBytes = 0; 4126 } 4127 4128 // FPDiff is the byte offset of the call's argument area from the callee's. 4129 // Stores to callee stack arguments will be placed in FixedStackSlots offset 4130 // by this amount for a tail call. In a sibling call it must be 0 because the 4131 // caller will deallocate the entire stack and the callee still expects its 4132 // arguments to begin at SP+0. Completely unused for non-tail calls. 4133 int FPDiff = 0; 4134 4135 if (IsTailCall && !IsSibCall) { 4136 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea(); 4137 4138 // Since callee will pop argument stack as a tail call, we must keep the 4139 // popped size 16-byte aligned. 4140 NumBytes = alignTo(NumBytes, 16); 4141 4142 // FPDiff will be negative if this tail call requires more space than we 4143 // would automatically have in our incoming argument space. Positive if we 4144 // can actually shrink the stack. 4145 FPDiff = NumReusableBytes - NumBytes; 4146 4147 // The stack pointer must be 16-byte aligned at all times it's used for a 4148 // memory operation, which in practice means at *all* times and in 4149 // particular across call boundaries. Therefore our own arguments started at 4150 // a 16-byte aligned SP and the delta applied for the tail call should 4151 // satisfy the same constraint. 4152 assert(FPDiff % 16 == 0 && "unaligned stack on tail call"); 4153 } 4154 4155 // Adjust the stack pointer for the new arguments... 4156 // These operations are automatically eliminated by the prolog/epilog pass 4157 if (!IsSibCall) 4158 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL); 4159 4160 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP, 4161 getPointerTy(DAG.getDataLayout())); 4162 4163 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 4164 SmallSet<unsigned, 8> RegsUsed; 4165 SmallVector<SDValue, 8> MemOpChains; 4166 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4167 4168 if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) { 4169 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms(); 4170 for (const auto &F : Forwards) { 4171 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT); 4172 RegsToPass.emplace_back(F.PReg, Val); 4173 } 4174 } 4175 4176 // Walk the register/memloc assignments, inserting copies/loads. 4177 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 4178 CCValAssign &VA = ArgLocs[i]; 4179 SDValue Arg = OutVals[i]; 4180 ISD::ArgFlagsTy Flags = Outs[i].Flags; 4181 4182 // Promote the value if needed. 4183 switch (VA.getLocInfo()) { 4184 default: 4185 llvm_unreachable("Unknown loc info!"); 4186 case CCValAssign::Full: 4187 break; 4188 case CCValAssign::SExt: 4189 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 4190 break; 4191 case CCValAssign::ZExt: 4192 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 4193 break; 4194 case CCValAssign::AExt: 4195 if (Outs[i].ArgVT == MVT::i1) { 4196 // AAPCS requires i1 to be zero-extended to 8-bits by the caller. 4197 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 4198 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg); 4199 } 4200 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 4201 break; 4202 case CCValAssign::AExtUpper: 4203 assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits"); 4204 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 4205 Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg, 4206 DAG.getConstant(32, DL, VA.getLocVT())); 4207 break; 4208 case CCValAssign::BCvt: 4209 Arg = DAG.getBitcast(VA.getLocVT(), Arg); 4210 break; 4211 case CCValAssign::Trunc: 4212 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT()); 4213 break; 4214 case CCValAssign::FPExt: 4215 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 4216 break; 4217 case CCValAssign::Indirect: 4218 assert(VA.getValVT().isScalableVector() && 4219 "Only scalable vectors can be passed indirectly"); 4220 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 4221 Type *Ty = EVT(VA.getValVT()).getTypeForEVT(*DAG.getContext()); 4222 unsigned Align = DAG.getDataLayout().getPrefTypeAlignment(Ty); 4223 int FI = MFI.CreateStackObject( 4224 VA.getValVT().getStoreSize().getKnownMinSize(), Align, false); 4225 MFI.setStackID(FI, TargetStackID::SVEVector); 4226 4227 SDValue SpillSlot = DAG.getFrameIndex( 4228 FI, DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout())); 4229 Chain = DAG.getStore( 4230 Chain, DL, Arg, SpillSlot, 4231 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)); 4232 Arg = SpillSlot; 4233 break; 4234 } 4235 4236 if (VA.isRegLoc()) { 4237 if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 4238 Outs[0].VT == MVT::i64) { 4239 assert(VA.getLocVT() == MVT::i64 && 4240 "unexpected calling convention register assignment"); 4241 assert(!Ins.empty() && Ins[0].VT == MVT::i64 && 4242 "unexpected use of 'returned'"); 4243 IsThisReturn = true; 4244 } 4245 if (RegsUsed.count(VA.getLocReg())) { 4246 // If this register has already been used then we're trying to pack 4247 // parts of an [N x i32] into an X-register. The extension type will 4248 // take care of putting the two halves in the right place but we have to 4249 // combine them. 4250 SDValue &Bits = 4251 std::find_if(RegsToPass.begin(), RegsToPass.end(), 4252 [=](const std::pair<unsigned, SDValue> &Elt) { 4253 return Elt.first == VA.getLocReg(); 4254 }) 4255 ->second; 4256 Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg); 4257 // Call site info is used for function's parameter entry value 4258 // tracking. For now we track only simple cases when parameter 4259 // is transferred through whole register. 4260 CSInfo.erase(std::remove_if(CSInfo.begin(), CSInfo.end(), 4261 [&VA](MachineFunction::ArgRegPair ArgReg) { 4262 return ArgReg.Reg == VA.getLocReg(); 4263 }), 4264 CSInfo.end()); 4265 } else { 4266 RegsToPass.emplace_back(VA.getLocReg(), Arg); 4267 RegsUsed.insert(VA.getLocReg()); 4268 const TargetOptions &Options = DAG.getTarget().Options; 4269 if (Options.EmitCallSiteInfo) 4270 CSInfo.emplace_back(VA.getLocReg(), i); 4271 } 4272 } else { 4273 assert(VA.isMemLoc()); 4274 4275 SDValue DstAddr; 4276 MachinePointerInfo DstInfo; 4277 4278 // FIXME: This works on big-endian for composite byvals, which are the 4279 // common case. It should also work for fundamental types too. 4280 uint32_t BEAlign = 0; 4281 unsigned OpSize; 4282 if (VA.getLocInfo() == CCValAssign::Indirect) 4283 OpSize = VA.getLocVT().getSizeInBits(); 4284 else 4285 OpSize = Flags.isByVal() ? Flags.getByValSize() * 8 4286 : VA.getValVT().getSizeInBits(); 4287 OpSize = (OpSize + 7) / 8; 4288 if (!Subtarget->isLittleEndian() && !Flags.isByVal() && 4289 !Flags.isInConsecutiveRegs()) { 4290 if (OpSize < 8) 4291 BEAlign = 8 - OpSize; 4292 } 4293 unsigned LocMemOffset = VA.getLocMemOffset(); 4294 int32_t Offset = LocMemOffset + BEAlign; 4295 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 4296 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 4297 4298 if (IsTailCall) { 4299 Offset = Offset + FPDiff; 4300 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 4301 4302 DstAddr = DAG.getFrameIndex(FI, PtrVT); 4303 DstInfo = 4304 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 4305 4306 // Make sure any stack arguments overlapping with where we're storing 4307 // are loaded before this eventual operation. Otherwise they'll be 4308 // clobbered. 4309 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI); 4310 } else { 4311 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 4312 4313 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 4314 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(), 4315 LocMemOffset); 4316 } 4317 4318 if (Outs[i].Flags.isByVal()) { 4319 SDValue SizeNode = 4320 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64); 4321 SDValue Cpy = DAG.getMemcpy( 4322 Chain, DL, DstAddr, Arg, SizeNode, 4323 Outs[i].Flags.getNonZeroByValAlign(), 4324 /*isVol = */ false, /*AlwaysInline = */ false, 4325 /*isTailCall = */ false, DstInfo, MachinePointerInfo()); 4326 4327 MemOpChains.push_back(Cpy); 4328 } else { 4329 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already 4330 // promoted to a legal register type i32, we should truncate Arg back to 4331 // i1/i8/i16. 4332 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 || 4333 VA.getValVT() == MVT::i16) 4334 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg); 4335 4336 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo); 4337 MemOpChains.push_back(Store); 4338 } 4339 } 4340 } 4341 4342 if (!MemOpChains.empty()) 4343 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 4344 4345 // Build a sequence of copy-to-reg nodes chained together with token chain 4346 // and flag operands which copy the outgoing args into the appropriate regs. 4347 SDValue InFlag; 4348 for (auto &RegToPass : RegsToPass) { 4349 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 4350 RegToPass.second, InFlag); 4351 InFlag = Chain.getValue(1); 4352 } 4353 4354 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 4355 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 4356 // node so that legalize doesn't hack it. 4357 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 4358 auto GV = G->getGlobal(); 4359 unsigned OpFlags = 4360 Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()); 4361 if (OpFlags & AArch64II::MO_GOT) { 4362 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 4363 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 4364 } else { 4365 const GlobalValue *GV = G->getGlobal(); 4366 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0); 4367 } 4368 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 4369 if (getTargetMachine().getCodeModel() == CodeModel::Large && 4370 Subtarget->isTargetMachO()) { 4371 const char *Sym = S->getSymbol(); 4372 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT); 4373 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 4374 } else { 4375 const char *Sym = S->getSymbol(); 4376 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0); 4377 } 4378 } 4379 4380 // We don't usually want to end the call-sequence here because we would tidy 4381 // the frame up *after* the call, however in the ABI-changing tail-call case 4382 // we've carefully laid out the parameters so that when sp is reset they'll be 4383 // in the correct location. 4384 if (IsTailCall && !IsSibCall) { 4385 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 4386 DAG.getIntPtrConstant(0, DL, true), InFlag, DL); 4387 InFlag = Chain.getValue(1); 4388 } 4389 4390 std::vector<SDValue> Ops; 4391 Ops.push_back(Chain); 4392 Ops.push_back(Callee); 4393 4394 if (IsTailCall) { 4395 // Each tail call may have to adjust the stack by a different amount, so 4396 // this information must travel along with the operation for eventual 4397 // consumption by emitEpilogue. 4398 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 4399 } 4400 4401 // Add argument registers to the end of the list so that they are known live 4402 // into the call. 4403 for (auto &RegToPass : RegsToPass) 4404 Ops.push_back(DAG.getRegister(RegToPass.first, 4405 RegToPass.second.getValueType())); 4406 4407 // Check callee args/returns for SVE registers and set calling convention 4408 // accordingly. 4409 if (CallConv == CallingConv::C) { 4410 bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){ 4411 return Out.VT.isScalableVector(); 4412 }); 4413 bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){ 4414 return In.VT.isScalableVector(); 4415 }); 4416 4417 if (CalleeInSVE || CalleeOutSVE) 4418 CallConv = CallingConv::AArch64_SVE_VectorCall; 4419 } 4420 4421 // Add a register mask operand representing the call-preserved registers. 4422 const uint32_t *Mask; 4423 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 4424 if (IsThisReturn) { 4425 // For 'this' returns, use the X0-preserving mask if applicable 4426 Mask = TRI->getThisReturnPreservedMask(MF, CallConv); 4427 if (!Mask) { 4428 IsThisReturn = false; 4429 Mask = TRI->getCallPreservedMask(MF, CallConv); 4430 } 4431 } else 4432 Mask = TRI->getCallPreservedMask(MF, CallConv); 4433 4434 if (Subtarget->hasCustomCallingConv()) 4435 TRI->UpdateCustomCallPreservedMask(MF, &Mask); 4436 4437 if (TRI->isAnyArgRegReserved(MF)) 4438 TRI->emitReservedArgRegCallError(MF); 4439 4440 assert(Mask && "Missing call preserved mask for calling convention"); 4441 Ops.push_back(DAG.getRegisterMask(Mask)); 4442 4443 if (InFlag.getNode()) 4444 Ops.push_back(InFlag); 4445 4446 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 4447 4448 // If we're doing a tall call, use a TC_RETURN here rather than an 4449 // actual call instruction. 4450 if (IsTailCall) { 4451 MF.getFrameInfo().setHasTailCall(); 4452 SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops); 4453 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo)); 4454 return Ret; 4455 } 4456 4457 // Returns a chain and a flag for retval copy to use. 4458 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops); 4459 InFlag = Chain.getValue(1); 4460 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo)); 4461 4462 uint64_t CalleePopBytes = 4463 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0; 4464 4465 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 4466 DAG.getIntPtrConstant(CalleePopBytes, DL, true), 4467 InFlag, DL); 4468 if (!Ins.empty()) 4469 InFlag = Chain.getValue(1); 4470 4471 // Handle result values, copying them out of physregs into vregs that we 4472 // return. 4473 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 4474 InVals, IsThisReturn, 4475 IsThisReturn ? OutVals[0] : SDValue()); 4476 } 4477 4478 bool AArch64TargetLowering::CanLowerReturn( 4479 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, 4480 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 4481 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 4482 ? RetCC_AArch64_WebKit_JS 4483 : RetCC_AArch64_AAPCS; 4484 SmallVector<CCValAssign, 16> RVLocs; 4485 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 4486 return CCInfo.CheckReturn(Outs, RetCC); 4487 } 4488 4489 SDValue 4490 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 4491 bool isVarArg, 4492 const SmallVectorImpl<ISD::OutputArg> &Outs, 4493 const SmallVectorImpl<SDValue> &OutVals, 4494 const SDLoc &DL, SelectionDAG &DAG) const { 4495 auto &MF = DAG.getMachineFunction(); 4496 auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 4497 4498 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 4499 ? RetCC_AArch64_WebKit_JS 4500 : RetCC_AArch64_AAPCS; 4501 SmallVector<CCValAssign, 16> RVLocs; 4502 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 4503 *DAG.getContext()); 4504 CCInfo.AnalyzeReturn(Outs, RetCC); 4505 4506 // Copy the result values into the output registers. 4507 SDValue Flag; 4508 SmallVector<std::pair<unsigned, SDValue>, 4> RetVals; 4509 SmallSet<unsigned, 4> RegsUsed; 4510 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size(); 4511 ++i, ++realRVLocIdx) { 4512 CCValAssign &VA = RVLocs[i]; 4513 assert(VA.isRegLoc() && "Can only return in registers!"); 4514 SDValue Arg = OutVals[realRVLocIdx]; 4515 4516 switch (VA.getLocInfo()) { 4517 default: 4518 llvm_unreachable("Unknown loc info!"); 4519 case CCValAssign::Full: 4520 if (Outs[i].ArgVT == MVT::i1) { 4521 // AAPCS requires i1 to be zero-extended to i8 by the producer of the 4522 // value. This is strictly redundant on Darwin (which uses "zeroext 4523 // i1"), but will be optimised out before ISel. 4524 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 4525 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 4526 } 4527 break; 4528 case CCValAssign::BCvt: 4529 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 4530 break; 4531 case CCValAssign::AExt: 4532 case CCValAssign::ZExt: 4533 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT()); 4534 break; 4535 case CCValAssign::AExtUpper: 4536 assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits"); 4537 Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT()); 4538 Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg, 4539 DAG.getConstant(32, DL, VA.getLocVT())); 4540 break; 4541 } 4542 4543 if (RegsUsed.count(VA.getLocReg())) { 4544 SDValue &Bits = 4545 std::find_if(RetVals.begin(), RetVals.end(), 4546 [=](const std::pair<unsigned, SDValue> &Elt) { 4547 return Elt.first == VA.getLocReg(); 4548 }) 4549 ->second; 4550 Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg); 4551 } else { 4552 RetVals.emplace_back(VA.getLocReg(), Arg); 4553 RegsUsed.insert(VA.getLocReg()); 4554 } 4555 } 4556 4557 SmallVector<SDValue, 4> RetOps(1, Chain); 4558 for (auto &RetVal : RetVals) { 4559 Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag); 4560 Flag = Chain.getValue(1); 4561 RetOps.push_back( 4562 DAG.getRegister(RetVal.first, RetVal.second.getValueType())); 4563 } 4564 4565 // Windows AArch64 ABIs require that for returning structs by value we copy 4566 // the sret argument into X0 for the return. 4567 // We saved the argument into a virtual register in the entry block, 4568 // so now we copy the value out and into X0. 4569 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) { 4570 SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg, 4571 getPointerTy(MF.getDataLayout())); 4572 4573 unsigned RetValReg = AArch64::X0; 4574 Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag); 4575 Flag = Chain.getValue(1); 4576 4577 RetOps.push_back( 4578 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout()))); 4579 } 4580 4581 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 4582 const MCPhysReg *I = 4583 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 4584 if (I) { 4585 for (; *I; ++I) { 4586 if (AArch64::GPR64RegClass.contains(*I)) 4587 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 4588 else if (AArch64::FPR64RegClass.contains(*I)) 4589 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 4590 else 4591 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 4592 } 4593 } 4594 4595 RetOps[0] = Chain; // Update chain. 4596 4597 // Add the flag if we have it. 4598 if (Flag.getNode()) 4599 RetOps.push_back(Flag); 4600 4601 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps); 4602 } 4603 4604 //===----------------------------------------------------------------------===// 4605 // Other Lowering Code 4606 //===----------------------------------------------------------------------===// 4607 4608 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty, 4609 SelectionDAG &DAG, 4610 unsigned Flag) const { 4611 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 4612 N->getOffset(), Flag); 4613 } 4614 4615 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty, 4616 SelectionDAG &DAG, 4617 unsigned Flag) const { 4618 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag); 4619 } 4620 4621 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty, 4622 SelectionDAG &DAG, 4623 unsigned Flag) const { 4624 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(), 4625 N->getOffset(), Flag); 4626 } 4627 4628 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty, 4629 SelectionDAG &DAG, 4630 unsigned Flag) const { 4631 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag); 4632 } 4633 4634 // (loadGOT sym) 4635 template <class NodeTy> 4636 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG, 4637 unsigned Flags) const { 4638 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n"); 4639 SDLoc DL(N); 4640 EVT Ty = getPointerTy(DAG.getDataLayout()); 4641 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags); 4642 // FIXME: Once remat is capable of dealing with instructions with register 4643 // operands, expand this into two nodes instead of using a wrapper node. 4644 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr); 4645 } 4646 4647 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym)) 4648 template <class NodeTy> 4649 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG, 4650 unsigned Flags) const { 4651 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n"); 4652 SDLoc DL(N); 4653 EVT Ty = getPointerTy(DAG.getDataLayout()); 4654 const unsigned char MO_NC = AArch64II::MO_NC; 4655 return DAG.getNode( 4656 AArch64ISD::WrapperLarge, DL, Ty, 4657 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags), 4658 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags), 4659 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags), 4660 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags)); 4661 } 4662 4663 // (addlow (adrp %hi(sym)) %lo(sym)) 4664 template <class NodeTy> 4665 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 4666 unsigned Flags) const { 4667 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n"); 4668 SDLoc DL(N); 4669 EVT Ty = getPointerTy(DAG.getDataLayout()); 4670 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags); 4671 SDValue Lo = getTargetNode(N, Ty, DAG, 4672 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags); 4673 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi); 4674 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo); 4675 } 4676 4677 // (adr sym) 4678 template <class NodeTy> 4679 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG, 4680 unsigned Flags) const { 4681 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n"); 4682 SDLoc DL(N); 4683 EVT Ty = getPointerTy(DAG.getDataLayout()); 4684 SDValue Sym = getTargetNode(N, Ty, DAG, Flags); 4685 return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym); 4686 } 4687 4688 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op, 4689 SelectionDAG &DAG) const { 4690 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op); 4691 const GlobalValue *GV = GN->getGlobal(); 4692 unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); 4693 4694 if (OpFlags != AArch64II::MO_NO_FLAG) 4695 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 && 4696 "unexpected offset in global node"); 4697 4698 // This also catches the large code model case for Darwin, and tiny code 4699 // model with got relocations. 4700 if ((OpFlags & AArch64II::MO_GOT) != 0) { 4701 return getGOT(GN, DAG, OpFlags); 4702 } 4703 4704 SDValue Result; 4705 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 4706 Result = getAddrLarge(GN, DAG, OpFlags); 4707 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 4708 Result = getAddrTiny(GN, DAG, OpFlags); 4709 } else { 4710 Result = getAddr(GN, DAG, OpFlags); 4711 } 4712 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4713 SDLoc DL(GN); 4714 if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB)) 4715 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 4716 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 4717 return Result; 4718 } 4719 4720 /// Convert a TLS address reference into the correct sequence of loads 4721 /// and calls to compute the variable's address (for Darwin, currently) and 4722 /// return an SDValue containing the final node. 4723 4724 /// Darwin only has one TLS scheme which must be capable of dealing with the 4725 /// fully general situation, in the worst case. This means: 4726 /// + "extern __thread" declaration. 4727 /// + Defined in a possibly unknown dynamic library. 4728 /// 4729 /// The general system is that each __thread variable has a [3 x i64] descriptor 4730 /// which contains information used by the runtime to calculate the address. The 4731 /// only part of this the compiler needs to know about is the first xword, which 4732 /// contains a function pointer that must be called with the address of the 4733 /// entire descriptor in "x0". 4734 /// 4735 /// Since this descriptor may be in a different unit, in general even the 4736 /// descriptor must be accessed via an indirect load. The "ideal" code sequence 4737 /// is: 4738 /// adrp x0, _var@TLVPPAGE 4739 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor 4740 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor, 4741 /// ; the function pointer 4742 /// blr x1 ; Uses descriptor address in x0 4743 /// ; Address of _var is now in x0. 4744 /// 4745 /// If the address of _var's descriptor *is* known to the linker, then it can 4746 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for 4747 /// a slight efficiency gain. 4748 SDValue 4749 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op, 4750 SelectionDAG &DAG) const { 4751 assert(Subtarget->isTargetDarwin() && 4752 "This function expects a Darwin target"); 4753 4754 SDLoc DL(Op); 4755 MVT PtrVT = getPointerTy(DAG.getDataLayout()); 4756 MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout()); 4757 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 4758 4759 SDValue TLVPAddr = 4760 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 4761 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr); 4762 4763 // The first entry in the descriptor is a function pointer that we must call 4764 // to obtain the address of the variable. 4765 SDValue Chain = DAG.getEntryNode(); 4766 SDValue FuncTLVGet = DAG.getLoad( 4767 PtrMemVT, DL, Chain, DescAddr, 4768 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 4769 /* Alignment = */ PtrMemVT.getSizeInBits() / 8, 4770 MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable); 4771 Chain = FuncTLVGet.getValue(1); 4772 4773 // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer. 4774 FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT); 4775 4776 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 4777 MFI.setAdjustsStack(true); 4778 4779 // TLS calls preserve all registers except those that absolutely must be 4780 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be 4781 // silly). 4782 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 4783 const uint32_t *Mask = TRI->getTLSCallPreservedMask(); 4784 if (Subtarget->hasCustomCallingConv()) 4785 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask); 4786 4787 // Finally, we can make the call. This is just a degenerate version of a 4788 // normal AArch64 call node: x0 takes the address of the descriptor, and 4789 // returns the address of the variable in this thread. 4790 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue()); 4791 Chain = 4792 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 4793 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64), 4794 DAG.getRegisterMask(Mask), Chain.getValue(1)); 4795 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1)); 4796 } 4797 4798 /// Convert a thread-local variable reference into a sequence of instructions to 4799 /// compute the variable's address for the local exec TLS model of ELF targets. 4800 /// The sequence depends on the maximum TLS area size. 4801 SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV, 4802 SDValue ThreadBase, 4803 const SDLoc &DL, 4804 SelectionDAG &DAG) const { 4805 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4806 SDValue TPOff, Addr; 4807 4808 switch (DAG.getTarget().Options.TLSSize) { 4809 default: 4810 llvm_unreachable("Unexpected TLS size"); 4811 4812 case 12: { 4813 // mrs x0, TPIDR_EL0 4814 // add x0, x0, :tprel_lo12:a 4815 SDValue Var = DAG.getTargetGlobalAddress( 4816 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF); 4817 return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase, 4818 Var, 4819 DAG.getTargetConstant(0, DL, MVT::i32)), 4820 0); 4821 } 4822 4823 case 24: { 4824 // mrs x0, TPIDR_EL0 4825 // add x0, x0, :tprel_hi12:a 4826 // add x0, x0, :tprel_lo12_nc:a 4827 SDValue HiVar = DAG.getTargetGlobalAddress( 4828 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 4829 SDValue LoVar = DAG.getTargetGlobalAddress( 4830 GV, DL, PtrVT, 0, 4831 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 4832 Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase, 4833 HiVar, 4834 DAG.getTargetConstant(0, DL, MVT::i32)), 4835 0); 4836 return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr, 4837 LoVar, 4838 DAG.getTargetConstant(0, DL, MVT::i32)), 4839 0); 4840 } 4841 4842 case 32: { 4843 // mrs x1, TPIDR_EL0 4844 // movz x0, #:tprel_g1:a 4845 // movk x0, #:tprel_g0_nc:a 4846 // add x0, x1, x0 4847 SDValue HiVar = DAG.getTargetGlobalAddress( 4848 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1); 4849 SDValue LoVar = DAG.getTargetGlobalAddress( 4850 GV, DL, PtrVT, 0, 4851 AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC); 4852 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar, 4853 DAG.getTargetConstant(16, DL, MVT::i32)), 4854 0); 4855 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar, 4856 DAG.getTargetConstant(0, DL, MVT::i32)), 4857 0); 4858 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 4859 } 4860 4861 case 48: { 4862 // mrs x1, TPIDR_EL0 4863 // movz x0, #:tprel_g2:a 4864 // movk x0, #:tprel_g1_nc:a 4865 // movk x0, #:tprel_g0_nc:a 4866 // add x0, x1, x0 4867 SDValue HiVar = DAG.getTargetGlobalAddress( 4868 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2); 4869 SDValue MiVar = DAG.getTargetGlobalAddress( 4870 GV, DL, PtrVT, 0, 4871 AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC); 4872 SDValue LoVar = DAG.getTargetGlobalAddress( 4873 GV, DL, PtrVT, 0, 4874 AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC); 4875 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar, 4876 DAG.getTargetConstant(32, DL, MVT::i32)), 4877 0); 4878 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar, 4879 DAG.getTargetConstant(16, DL, MVT::i32)), 4880 0); 4881 TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar, 4882 DAG.getTargetConstant(0, DL, MVT::i32)), 4883 0); 4884 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 4885 } 4886 } 4887 } 4888 4889 /// When accessing thread-local variables under either the general-dynamic or 4890 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will 4891 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry 4892 /// is a function pointer to carry out the resolution. 4893 /// 4894 /// The sequence is: 4895 /// adrp x0, :tlsdesc:var 4896 /// ldr x1, [x0, #:tlsdesc_lo12:var] 4897 /// add x0, x0, #:tlsdesc_lo12:var 4898 /// .tlsdesccall var 4899 /// blr x1 4900 /// (TPIDR_EL0 offset now in x0) 4901 /// 4902 /// The above sequence must be produced unscheduled, to enable the linker to 4903 /// optimize/relax this sequence. 4904 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the 4905 /// above sequence, and expanded really late in the compilation flow, to ensure 4906 /// the sequence is produced as per above. 4907 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, 4908 const SDLoc &DL, 4909 SelectionDAG &DAG) const { 4910 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4911 4912 SDValue Chain = DAG.getEntryNode(); 4913 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 4914 4915 Chain = 4916 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr}); 4917 SDValue Glue = Chain.getValue(1); 4918 4919 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue); 4920 } 4921 4922 SDValue 4923 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op, 4924 SelectionDAG &DAG) const { 4925 assert(Subtarget->isTargetELF() && "This function expects an ELF target"); 4926 4927 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 4928 4929 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal()); 4930 4931 if (!EnableAArch64ELFLocalDynamicTLSGeneration) { 4932 if (Model == TLSModel::LocalDynamic) 4933 Model = TLSModel::GeneralDynamic; 4934 } 4935 4936 if (getTargetMachine().getCodeModel() == CodeModel::Large && 4937 Model != TLSModel::LocalExec) 4938 report_fatal_error("ELF TLS only supported in small memory model or " 4939 "in local exec TLS model"); 4940 // Different choices can be made for the maximum size of the TLS area for a 4941 // module. For the small address model, the default TLS size is 16MiB and the 4942 // maximum TLS size is 4GiB. 4943 // FIXME: add tiny and large code model support for TLS access models other 4944 // than local exec. We currently generate the same code as small for tiny, 4945 // which may be larger than needed. 4946 4947 SDValue TPOff; 4948 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4949 SDLoc DL(Op); 4950 const GlobalValue *GV = GA->getGlobal(); 4951 4952 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT); 4953 4954 if (Model == TLSModel::LocalExec) { 4955 return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG); 4956 } else if (Model == TLSModel::InitialExec) { 4957 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 4958 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff); 4959 } else if (Model == TLSModel::LocalDynamic) { 4960 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS 4961 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate 4962 // the beginning of the module's TLS region, followed by a DTPREL offset 4963 // calculation. 4964 4965 // These accesses will need deduplicating if there's more than one. 4966 AArch64FunctionInfo *MFI = 4967 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 4968 MFI->incNumLocalDynamicTLSAccesses(); 4969 4970 // The call needs a relocation too for linker relaxation. It doesn't make 4971 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 4972 // the address. 4973 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT, 4974 AArch64II::MO_TLS); 4975 4976 // Now we can calculate the offset from TPIDR_EL0 to this module's 4977 // thread-local area. 4978 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 4979 4980 // Now use :dtprel_whatever: operations to calculate this variable's offset 4981 // in its thread-storage area. 4982 SDValue HiVar = DAG.getTargetGlobalAddress( 4983 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 4984 SDValue LoVar = DAG.getTargetGlobalAddress( 4985 GV, DL, MVT::i64, 0, 4986 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 4987 4988 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar, 4989 DAG.getTargetConstant(0, DL, MVT::i32)), 4990 0); 4991 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar, 4992 DAG.getTargetConstant(0, DL, MVT::i32)), 4993 0); 4994 } else if (Model == TLSModel::GeneralDynamic) { 4995 // The call needs a relocation too for linker relaxation. It doesn't make 4996 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 4997 // the address. 4998 SDValue SymAddr = 4999 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 5000 5001 // Finally we can make a call to calculate the offset from tpidr_el0. 5002 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 5003 } else 5004 llvm_unreachable("Unsupported ELF TLS access model"); 5005 5006 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 5007 } 5008 5009 SDValue 5010 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op, 5011 SelectionDAG &DAG) const { 5012 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 5013 5014 SDValue Chain = DAG.getEntryNode(); 5015 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 5016 SDLoc DL(Op); 5017 5018 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64); 5019 5020 // Load the ThreadLocalStoragePointer from the TEB 5021 // A pointer to the TLS array is located at offset 0x58 from the TEB. 5022 SDValue TLSArray = 5023 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL)); 5024 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 5025 Chain = TLSArray.getValue(1); 5026 5027 // Load the TLS index from the C runtime; 5028 // This does the same as getAddr(), but without having a GlobalAddressSDNode. 5029 // This also does the same as LOADgot, but using a generic i32 load, 5030 // while LOADgot only loads i64. 5031 SDValue TLSIndexHi = 5032 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE); 5033 SDValue TLSIndexLo = DAG.getTargetExternalSymbol( 5034 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 5035 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi); 5036 SDValue TLSIndex = 5037 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo); 5038 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo()); 5039 Chain = TLSIndex.getValue(1); 5040 5041 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8 5042 // offset into the TLSArray. 5043 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex); 5044 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 5045 DAG.getConstant(3, DL, PtrVT)); 5046 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 5047 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 5048 MachinePointerInfo()); 5049 Chain = TLS.getValue(1); 5050 5051 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 5052 const GlobalValue *GV = GA->getGlobal(); 5053 SDValue TGAHi = DAG.getTargetGlobalAddress( 5054 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 5055 SDValue TGALo = DAG.getTargetGlobalAddress( 5056 GV, DL, PtrVT, 0, 5057 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 5058 5059 // Add the offset from the start of the .tls section (section base). 5060 SDValue Addr = 5061 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi, 5062 DAG.getTargetConstant(0, DL, MVT::i32)), 5063 0); 5064 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo); 5065 return Addr; 5066 } 5067 5068 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op, 5069 SelectionDAG &DAG) const { 5070 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 5071 if (DAG.getTarget().useEmulatedTLS()) 5072 return LowerToTLSEmulatedModel(GA, DAG); 5073 5074 if (Subtarget->isTargetDarwin()) 5075 return LowerDarwinGlobalTLSAddress(Op, DAG); 5076 if (Subtarget->isTargetELF()) 5077 return LowerELFGlobalTLSAddress(Op, DAG); 5078 if (Subtarget->isTargetWindows()) 5079 return LowerWindowsGlobalTLSAddress(Op, DAG); 5080 5081 llvm_unreachable("Unexpected platform trying to use TLS"); 5082 } 5083 5084 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 5085 SDValue Chain = Op.getOperand(0); 5086 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 5087 SDValue LHS = Op.getOperand(2); 5088 SDValue RHS = Op.getOperand(3); 5089 SDValue Dest = Op.getOperand(4); 5090 SDLoc dl(Op); 5091 5092 MachineFunction &MF = DAG.getMachineFunction(); 5093 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions 5094 // will not be produced, as they are conditional branch instructions that do 5095 // not set flags. 5096 bool ProduceNonFlagSettingCondBr = 5097 !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening); 5098 5099 // Handle f128 first, since lowering it will result in comparing the return 5100 // value of a libcall against zero, which is just what the rest of LowerBR_CC 5101 // is expecting to deal with. 5102 if (LHS.getValueType() == MVT::f128) { 5103 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS); 5104 5105 // If softenSetCCOperands returned a scalar, we need to compare the result 5106 // against zero to select between true and false values. 5107 if (!RHS.getNode()) { 5108 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 5109 CC = ISD::SETNE; 5110 } 5111 } 5112 5113 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 5114 // instruction. 5115 if (ISD::isOverflowIntrOpRes(LHS) && isOneConstant(RHS) && 5116 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 5117 // Only lower legal XALUO ops. 5118 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 5119 return SDValue(); 5120 5121 // The actual operation with overflow check. 5122 AArch64CC::CondCode OFCC; 5123 SDValue Value, Overflow; 5124 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG); 5125 5126 if (CC == ISD::SETNE) 5127 OFCC = getInvertedCondCode(OFCC); 5128 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32); 5129 5130 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 5131 Overflow); 5132 } 5133 5134 if (LHS.getValueType().isInteger()) { 5135 assert((LHS.getValueType() == RHS.getValueType()) && 5136 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 5137 5138 // If the RHS of the comparison is zero, we can potentially fold this 5139 // to a specialized branch. 5140 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS); 5141 if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) { 5142 if (CC == ISD::SETEQ) { 5143 // See if we can use a TBZ to fold in an AND as well. 5144 // TBZ has a smaller branch displacement than CBZ. If the offset is 5145 // out of bounds, a late MI-layer pass rewrites branches. 5146 // 403.gcc is an example that hits this case. 5147 if (LHS.getOpcode() == ISD::AND && 5148 isa<ConstantSDNode>(LHS.getOperand(1)) && 5149 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 5150 SDValue Test = LHS.getOperand(0); 5151 uint64_t Mask = LHS.getConstantOperandVal(1); 5152 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test, 5153 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 5154 Dest); 5155 } 5156 5157 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest); 5158 } else if (CC == ISD::SETNE) { 5159 // See if we can use a TBZ to fold in an AND as well. 5160 // TBZ has a smaller branch displacement than CBZ. If the offset is 5161 // out of bounds, a late MI-layer pass rewrites branches. 5162 // 403.gcc is an example that hits this case. 5163 if (LHS.getOpcode() == ISD::AND && 5164 isa<ConstantSDNode>(LHS.getOperand(1)) && 5165 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 5166 SDValue Test = LHS.getOperand(0); 5167 uint64_t Mask = LHS.getConstantOperandVal(1); 5168 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test, 5169 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 5170 Dest); 5171 } 5172 5173 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest); 5174 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) { 5175 // Don't combine AND since emitComparison converts the AND to an ANDS 5176 // (a.k.a. TST) and the test in the test bit and branch instruction 5177 // becomes redundant. This would also increase register pressure. 5178 uint64_t Mask = LHS.getValueSizeInBits() - 1; 5179 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS, 5180 DAG.getConstant(Mask, dl, MVT::i64), Dest); 5181 } 5182 } 5183 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT && 5184 LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) { 5185 // Don't combine AND since emitComparison converts the AND to an ANDS 5186 // (a.k.a. TST) and the test in the test bit and branch instruction 5187 // becomes redundant. This would also increase register pressure. 5188 uint64_t Mask = LHS.getValueSizeInBits() - 1; 5189 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS, 5190 DAG.getConstant(Mask, dl, MVT::i64), Dest); 5191 } 5192 5193 SDValue CCVal; 5194 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 5195 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 5196 Cmp); 5197 } 5198 5199 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 5200 LHS.getValueType() == MVT::f64); 5201 5202 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 5203 // clean. Some of them require two branches to implement. 5204 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 5205 AArch64CC::CondCode CC1, CC2; 5206 changeFPCCToAArch64CC(CC, CC1, CC2); 5207 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 5208 SDValue BR1 = 5209 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp); 5210 if (CC2 != AArch64CC::AL) { 5211 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 5212 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val, 5213 Cmp); 5214 } 5215 5216 return BR1; 5217 } 5218 5219 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op, 5220 SelectionDAG &DAG) const { 5221 EVT VT = Op.getValueType(); 5222 SDLoc DL(Op); 5223 5224 SDValue In1 = Op.getOperand(0); 5225 SDValue In2 = Op.getOperand(1); 5226 EVT SrcVT = In2.getValueType(); 5227 5228 if (SrcVT.bitsLT(VT)) 5229 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2); 5230 else if (SrcVT.bitsGT(VT)) 5231 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL)); 5232 5233 EVT VecVT; 5234 uint64_t EltMask; 5235 SDValue VecVal1, VecVal2; 5236 5237 auto setVecVal = [&] (int Idx) { 5238 if (!VT.isVector()) { 5239 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT, 5240 DAG.getUNDEF(VecVT), In1); 5241 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT, 5242 DAG.getUNDEF(VecVT), In2); 5243 } else { 5244 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1); 5245 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2); 5246 } 5247 }; 5248 5249 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) { 5250 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32); 5251 EltMask = 0x80000000ULL; 5252 setVecVal(AArch64::ssub); 5253 } else if (VT == MVT::f64 || VT == MVT::v2f64) { 5254 VecVT = MVT::v2i64; 5255 5256 // We want to materialize a mask with the high bit set, but the AdvSIMD 5257 // immediate moves cannot materialize that in a single instruction for 5258 // 64-bit elements. Instead, materialize zero and then negate it. 5259 EltMask = 0; 5260 5261 setVecVal(AArch64::dsub); 5262 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) { 5263 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16); 5264 EltMask = 0x8000ULL; 5265 setVecVal(AArch64::hsub); 5266 } else { 5267 llvm_unreachable("Invalid type for copysign!"); 5268 } 5269 5270 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT); 5271 5272 // If we couldn't materialize the mask above, then the mask vector will be 5273 // the zero vector, and we need to negate it here. 5274 if (VT == MVT::f64 || VT == MVT::v2f64) { 5275 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec); 5276 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec); 5277 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec); 5278 } 5279 5280 SDValue Sel = 5281 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec); 5282 5283 if (VT == MVT::f16) 5284 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel); 5285 if (VT == MVT::f32) 5286 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel); 5287 else if (VT == MVT::f64) 5288 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel); 5289 else 5290 return DAG.getNode(ISD::BITCAST, DL, VT, Sel); 5291 } 5292 5293 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const { 5294 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 5295 Attribute::NoImplicitFloat)) 5296 return SDValue(); 5297 5298 if (!Subtarget->hasNEON()) 5299 return SDValue(); 5300 5301 // While there is no integer popcount instruction, it can 5302 // be more efficiently lowered to the following sequence that uses 5303 // AdvSIMD registers/instructions as long as the copies to/from 5304 // the AdvSIMD registers are cheap. 5305 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd 5306 // CNT V0.8B, V0.8B // 8xbyte pop-counts 5307 // ADDV B0, V0.8B // sum 8xbyte pop-counts 5308 // UMOV X0, V0.B[0] // copy byte result back to integer reg 5309 SDValue Val = Op.getOperand(0); 5310 SDLoc DL(Op); 5311 EVT VT = Op.getValueType(); 5312 5313 if (VT == MVT::i32 || VT == MVT::i64) { 5314 if (VT == MVT::i32) 5315 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val); 5316 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val); 5317 5318 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val); 5319 SDValue UaddLV = DAG.getNode( 5320 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, 5321 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop); 5322 5323 if (VT == MVT::i64) 5324 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV); 5325 return UaddLV; 5326 } 5327 5328 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || 5329 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && 5330 "Unexpected type for custom ctpop lowering"); 5331 5332 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 5333 Val = DAG.getBitcast(VT8Bit, Val); 5334 Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val); 5335 5336 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds. 5337 unsigned EltSize = 8; 5338 unsigned NumElts = VT.is64BitVector() ? 8 : 16; 5339 while (EltSize != VT.getScalarSizeInBits()) { 5340 EltSize *= 2; 5341 NumElts /= 2; 5342 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts); 5343 Val = DAG.getNode( 5344 ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, 5345 DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val); 5346 } 5347 5348 return Val; 5349 } 5350 5351 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 5352 5353 if (Op.getValueType().isVector()) 5354 return LowerVSETCC(Op, DAG); 5355 5356 bool IsStrict = Op->isStrictFPOpcode(); 5357 bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS; 5358 unsigned OpNo = IsStrict ? 1 : 0; 5359 SDValue Chain; 5360 if (IsStrict) 5361 Chain = Op.getOperand(0); 5362 SDValue LHS = Op.getOperand(OpNo + 0); 5363 SDValue RHS = Op.getOperand(OpNo + 1); 5364 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(OpNo + 2))->get(); 5365 SDLoc dl(Op); 5366 5367 // We chose ZeroOrOneBooleanContents, so use zero and one. 5368 EVT VT = Op.getValueType(); 5369 SDValue TVal = DAG.getConstant(1, dl, VT); 5370 SDValue FVal = DAG.getConstant(0, dl, VT); 5371 5372 // Handle f128 first, since one possible outcome is a normal integer 5373 // comparison which gets picked up by the next if statement. 5374 if (LHS.getValueType() == MVT::f128) { 5375 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS, Chain, 5376 IsSignaling); 5377 5378 // If softenSetCCOperands returned a scalar, use it. 5379 if (!RHS.getNode()) { 5380 assert(LHS.getValueType() == Op.getValueType() && 5381 "Unexpected setcc expansion!"); 5382 return IsStrict ? DAG.getMergeValues({LHS, Chain}, dl) : LHS; 5383 } 5384 } 5385 5386 if (LHS.getValueType().isInteger()) { 5387 SDValue CCVal; 5388 SDValue Cmp = getAArch64Cmp( 5389 LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl); 5390 5391 // Note that we inverted the condition above, so we reverse the order of 5392 // the true and false operands here. This will allow the setcc to be 5393 // matched to a single CSINC instruction. 5394 SDValue Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp); 5395 return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res; 5396 } 5397 5398 // Now we know we're dealing with FP values. 5399 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 5400 LHS.getValueType() == MVT::f64); 5401 5402 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead 5403 // and do the comparison. 5404 SDValue Cmp; 5405 if (IsStrict) 5406 Cmp = emitStrictFPComparison(LHS, RHS, dl, DAG, Chain, IsSignaling); 5407 else 5408 Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 5409 5410 AArch64CC::CondCode CC1, CC2; 5411 changeFPCCToAArch64CC(CC, CC1, CC2); 5412 SDValue Res; 5413 if (CC2 == AArch64CC::AL) { 5414 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1, 5415 CC2); 5416 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 5417 5418 // Note that we inverted the condition above, so we reverse the order of 5419 // the true and false operands here. This will allow the setcc to be 5420 // matched to a single CSINC instruction. 5421 Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp); 5422 } else { 5423 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't 5424 // totally clean. Some of them require two CSELs to implement. As is in 5425 // this case, we emit the first CSEL and then emit a second using the output 5426 // of the first as the RHS. We're effectively OR'ing the two CC's together. 5427 5428 // FIXME: It would be nice if we could match the two CSELs to two CSINCs. 5429 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 5430 SDValue CS1 = 5431 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 5432 5433 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 5434 Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 5435 } 5436 return IsStrict ? DAG.getMergeValues({Res, Cmp.getValue(1)}, dl) : Res; 5437 } 5438 5439 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS, 5440 SDValue RHS, SDValue TVal, 5441 SDValue FVal, const SDLoc &dl, 5442 SelectionDAG &DAG) const { 5443 // Handle f128 first, because it will result in a comparison of some RTLIB 5444 // call result against zero. 5445 if (LHS.getValueType() == MVT::f128) { 5446 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS); 5447 5448 // If softenSetCCOperands returned a scalar, we need to compare the result 5449 // against zero to select between true and false values. 5450 if (!RHS.getNode()) { 5451 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 5452 CC = ISD::SETNE; 5453 } 5454 } 5455 5456 // Also handle f16, for which we need to do a f32 comparison. 5457 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) { 5458 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 5459 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 5460 } 5461 5462 // Next, handle integers. 5463 if (LHS.getValueType().isInteger()) { 5464 assert((LHS.getValueType() == RHS.getValueType()) && 5465 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 5466 5467 unsigned Opcode = AArch64ISD::CSEL; 5468 5469 // If both the TVal and the FVal are constants, see if we can swap them in 5470 // order to for a CSINV or CSINC out of them. 5471 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 5472 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 5473 5474 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) { 5475 std::swap(TVal, FVal); 5476 std::swap(CTVal, CFVal); 5477 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5478 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) { 5479 std::swap(TVal, FVal); 5480 std::swap(CTVal, CFVal); 5481 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5482 } else if (TVal.getOpcode() == ISD::XOR) { 5483 // If TVal is a NOT we want to swap TVal and FVal so that we can match 5484 // with a CSINV rather than a CSEL. 5485 if (isAllOnesConstant(TVal.getOperand(1))) { 5486 std::swap(TVal, FVal); 5487 std::swap(CTVal, CFVal); 5488 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5489 } 5490 } else if (TVal.getOpcode() == ISD::SUB) { 5491 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so 5492 // that we can match with a CSNEG rather than a CSEL. 5493 if (isNullConstant(TVal.getOperand(0))) { 5494 std::swap(TVal, FVal); 5495 std::swap(CTVal, CFVal); 5496 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5497 } 5498 } else if (CTVal && CFVal) { 5499 const int64_t TrueVal = CTVal->getSExtValue(); 5500 const int64_t FalseVal = CFVal->getSExtValue(); 5501 bool Swap = false; 5502 5503 // If both TVal and FVal are constants, see if FVal is the 5504 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC 5505 // instead of a CSEL in that case. 5506 if (TrueVal == ~FalseVal) { 5507 Opcode = AArch64ISD::CSINV; 5508 } else if (TrueVal == -FalseVal) { 5509 Opcode = AArch64ISD::CSNEG; 5510 } else if (TVal.getValueType() == MVT::i32) { 5511 // If our operands are only 32-bit wide, make sure we use 32-bit 5512 // arithmetic for the check whether we can use CSINC. This ensures that 5513 // the addition in the check will wrap around properly in case there is 5514 // an overflow (which would not be the case if we do the check with 5515 // 64-bit arithmetic). 5516 const uint32_t TrueVal32 = CTVal->getZExtValue(); 5517 const uint32_t FalseVal32 = CFVal->getZExtValue(); 5518 5519 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) { 5520 Opcode = AArch64ISD::CSINC; 5521 5522 if (TrueVal32 > FalseVal32) { 5523 Swap = true; 5524 } 5525 } 5526 // 64-bit check whether we can use CSINC. 5527 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) { 5528 Opcode = AArch64ISD::CSINC; 5529 5530 if (TrueVal > FalseVal) { 5531 Swap = true; 5532 } 5533 } 5534 5535 // Swap TVal and FVal if necessary. 5536 if (Swap) { 5537 std::swap(TVal, FVal); 5538 std::swap(CTVal, CFVal); 5539 CC = ISD::getSetCCInverse(CC, LHS.getValueType()); 5540 } 5541 5542 if (Opcode != AArch64ISD::CSEL) { 5543 // Drop FVal since we can get its value by simply inverting/negating 5544 // TVal. 5545 FVal = TVal; 5546 } 5547 } 5548 5549 // Avoid materializing a constant when possible by reusing a known value in 5550 // a register. However, don't perform this optimization if the known value 5551 // is one, zero or negative one in the case of a CSEL. We can always 5552 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the 5553 // FVal, respectively. 5554 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS); 5555 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() && 5556 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) { 5557 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 5558 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to 5559 // "a != C ? x : a" to avoid materializing C. 5560 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ) 5561 TVal = LHS; 5562 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE) 5563 FVal = LHS; 5564 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) { 5565 assert (CTVal && CFVal && "Expected constant operands for CSNEG."); 5566 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to 5567 // avoid materializing C. 5568 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 5569 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) { 5570 Opcode = AArch64ISD::CSINV; 5571 TVal = LHS; 5572 FVal = DAG.getConstant(0, dl, FVal.getValueType()); 5573 } 5574 } 5575 5576 SDValue CCVal; 5577 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 5578 EVT VT = TVal.getValueType(); 5579 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp); 5580 } 5581 5582 // Now we know we're dealing with FP values. 5583 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 5584 LHS.getValueType() == MVT::f64); 5585 assert(LHS.getValueType() == RHS.getValueType()); 5586 EVT VT = TVal.getValueType(); 5587 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 5588 5589 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 5590 // clean. Some of them require two CSELs to implement. 5591 AArch64CC::CondCode CC1, CC2; 5592 changeFPCCToAArch64CC(CC, CC1, CC2); 5593 5594 if (DAG.getTarget().Options.UnsafeFPMath) { 5595 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and 5596 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0. 5597 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS); 5598 if (RHSVal && RHSVal->isZero()) { 5599 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal); 5600 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal); 5601 5602 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) && 5603 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType()) 5604 TVal = LHS; 5605 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) && 5606 CFVal && CFVal->isZero() && 5607 FVal.getValueType() == LHS.getValueType()) 5608 FVal = LHS; 5609 } 5610 } 5611 5612 // Emit first, and possibly only, CSEL. 5613 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 5614 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 5615 5616 // If we need a second CSEL, emit it, using the output of the first as the 5617 // RHS. We're effectively OR'ing the two CC's together. 5618 if (CC2 != AArch64CC::AL) { 5619 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 5620 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 5621 } 5622 5623 // Otherwise, return the output of the first CSEL. 5624 return CS1; 5625 } 5626 5627 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op, 5628 SelectionDAG &DAG) const { 5629 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 5630 SDValue LHS = Op.getOperand(0); 5631 SDValue RHS = Op.getOperand(1); 5632 SDValue TVal = Op.getOperand(2); 5633 SDValue FVal = Op.getOperand(3); 5634 SDLoc DL(Op); 5635 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 5636 } 5637 5638 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op, 5639 SelectionDAG &DAG) const { 5640 SDValue CCVal = Op->getOperand(0); 5641 SDValue TVal = Op->getOperand(1); 5642 SDValue FVal = Op->getOperand(2); 5643 SDLoc DL(Op); 5644 5645 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select 5646 // instruction. 5647 if (ISD::isOverflowIntrOpRes(CCVal)) { 5648 // Only lower legal XALUO ops. 5649 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0))) 5650 return SDValue(); 5651 5652 AArch64CC::CondCode OFCC; 5653 SDValue Value, Overflow; 5654 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG); 5655 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32); 5656 5657 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, 5658 CCVal, Overflow); 5659 } 5660 5661 // Lower it the same way as we would lower a SELECT_CC node. 5662 ISD::CondCode CC; 5663 SDValue LHS, RHS; 5664 if (CCVal.getOpcode() == ISD::SETCC) { 5665 LHS = CCVal.getOperand(0); 5666 RHS = CCVal.getOperand(1); 5667 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get(); 5668 } else { 5669 LHS = CCVal; 5670 RHS = DAG.getConstant(0, DL, CCVal.getValueType()); 5671 CC = ISD::SETNE; 5672 } 5673 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 5674 } 5675 5676 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op, 5677 SelectionDAG &DAG) const { 5678 // Jump table entries as PC relative offsets. No additional tweaking 5679 // is necessary here. Just get the address of the jump table. 5680 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 5681 5682 if (getTargetMachine().getCodeModel() == CodeModel::Large && 5683 !Subtarget->isTargetMachO()) { 5684 return getAddrLarge(JT, DAG); 5685 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 5686 return getAddrTiny(JT, DAG); 5687 } 5688 return getAddr(JT, DAG); 5689 } 5690 5691 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op, 5692 SelectionDAG &DAG) const { 5693 // Jump table entries as PC relative offsets. No additional tweaking 5694 // is necessary here. Just get the address of the jump table. 5695 SDLoc DL(Op); 5696 SDValue JT = Op.getOperand(1); 5697 SDValue Entry = Op.getOperand(2); 5698 int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex(); 5699 5700 SDNode *Dest = 5701 DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT, 5702 Entry, DAG.getTargetJumpTable(JTI, MVT::i32)); 5703 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0), 5704 SDValue(Dest, 0)); 5705 } 5706 5707 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op, 5708 SelectionDAG &DAG) const { 5709 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 5710 5711 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 5712 // Use the GOT for the large code model on iOS. 5713 if (Subtarget->isTargetMachO()) { 5714 return getGOT(CP, DAG); 5715 } 5716 return getAddrLarge(CP, DAG); 5717 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 5718 return getAddrTiny(CP, DAG); 5719 } else { 5720 return getAddr(CP, DAG); 5721 } 5722 } 5723 5724 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op, 5725 SelectionDAG &DAG) const { 5726 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op); 5727 if (getTargetMachine().getCodeModel() == CodeModel::Large && 5728 !Subtarget->isTargetMachO()) { 5729 return getAddrLarge(BA, DAG); 5730 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 5731 return getAddrTiny(BA, DAG); 5732 } 5733 return getAddr(BA, DAG); 5734 } 5735 5736 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op, 5737 SelectionDAG &DAG) const { 5738 AArch64FunctionInfo *FuncInfo = 5739 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 5740 5741 SDLoc DL(Op); 5742 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), 5743 getPointerTy(DAG.getDataLayout())); 5744 FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout())); 5745 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 5746 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 5747 MachinePointerInfo(SV)); 5748 } 5749 5750 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op, 5751 SelectionDAG &DAG) const { 5752 AArch64FunctionInfo *FuncInfo = 5753 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 5754 5755 SDLoc DL(Op); 5756 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0 5757 ? FuncInfo->getVarArgsGPRIndex() 5758 : FuncInfo->getVarArgsStackIndex(), 5759 getPointerTy(DAG.getDataLayout())); 5760 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 5761 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 5762 MachinePointerInfo(SV)); 5763 } 5764 5765 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op, 5766 SelectionDAG &DAG) const { 5767 // The layout of the va_list struct is specified in the AArch64 Procedure Call 5768 // Standard, section B.3. 5769 MachineFunction &MF = DAG.getMachineFunction(); 5770 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 5771 auto PtrVT = getPointerTy(DAG.getDataLayout()); 5772 SDLoc DL(Op); 5773 5774 SDValue Chain = Op.getOperand(0); 5775 SDValue VAList = Op.getOperand(1); 5776 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 5777 SmallVector<SDValue, 4> MemOps; 5778 5779 // void *__stack at offset 0 5780 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT); 5781 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList, 5782 MachinePointerInfo(SV), /* Alignment = */ 8)); 5783 5784 // void *__gr_top at offset 8 5785 int GPRSize = FuncInfo->getVarArgsGPRSize(); 5786 if (GPRSize > 0) { 5787 SDValue GRTop, GRTopAddr; 5788 5789 GRTopAddr = 5790 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT)); 5791 5792 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT); 5793 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop, 5794 DAG.getConstant(GPRSize, DL, PtrVT)); 5795 5796 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr, 5797 MachinePointerInfo(SV, 8), 5798 /* Alignment = */ 8)); 5799 } 5800 5801 // void *__vr_top at offset 16 5802 int FPRSize = FuncInfo->getVarArgsFPRSize(); 5803 if (FPRSize > 0) { 5804 SDValue VRTop, VRTopAddr; 5805 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 5806 DAG.getConstant(16, DL, PtrVT)); 5807 5808 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT); 5809 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop, 5810 DAG.getConstant(FPRSize, DL, PtrVT)); 5811 5812 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr, 5813 MachinePointerInfo(SV, 16), 5814 /* Alignment = */ 8)); 5815 } 5816 5817 // int __gr_offs at offset 24 5818 SDValue GROffsAddr = 5819 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT)); 5820 MemOps.push_back(DAG.getStore( 5821 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr, 5822 MachinePointerInfo(SV, 24), /* Alignment = */ 4)); 5823 5824 // int __vr_offs at offset 28 5825 SDValue VROffsAddr = 5826 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT)); 5827 MemOps.push_back(DAG.getStore( 5828 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr, 5829 MachinePointerInfo(SV, 28), /* Alignment = */ 4)); 5830 5831 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 5832 } 5833 5834 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op, 5835 SelectionDAG &DAG) const { 5836 MachineFunction &MF = DAG.getMachineFunction(); 5837 5838 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv())) 5839 return LowerWin64_VASTART(Op, DAG); 5840 else if (Subtarget->isTargetDarwin()) 5841 return LowerDarwin_VASTART(Op, DAG); 5842 else 5843 return LowerAAPCS_VASTART(Op, DAG); 5844 } 5845 5846 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op, 5847 SelectionDAG &DAG) const { 5848 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single 5849 // pointer. 5850 SDLoc DL(Op); 5851 unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8; 5852 unsigned VaListSize = (Subtarget->isTargetDarwin() || 5853 Subtarget->isTargetWindows()) ? PtrSize : 32; 5854 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 5855 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 5856 5857 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2), 5858 DAG.getConstant(VaListSize, DL, MVT::i32), 5859 Align(PtrSize), false, false, false, 5860 MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV)); 5861 } 5862 5863 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 5864 assert(Subtarget->isTargetDarwin() && 5865 "automatic va_arg instruction only works on Darwin"); 5866 5867 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 5868 EVT VT = Op.getValueType(); 5869 SDLoc DL(Op); 5870 SDValue Chain = Op.getOperand(0); 5871 SDValue Addr = Op.getOperand(1); 5872 unsigned Align = Op.getConstantOperandVal(3); 5873 unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8; 5874 auto PtrVT = getPointerTy(DAG.getDataLayout()); 5875 auto PtrMemVT = getPointerMemTy(DAG.getDataLayout()); 5876 SDValue VAList = 5877 DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V)); 5878 Chain = VAList.getValue(1); 5879 VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT); 5880 5881 if (Align > MinSlotSize) { 5882 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2"); 5883 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 5884 DAG.getConstant(Align - 1, DL, PtrVT)); 5885 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList, 5886 DAG.getConstant(-(int64_t)Align, DL, PtrVT)); 5887 } 5888 5889 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 5890 unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy); 5891 5892 // Scalar integer and FP values smaller than 64 bits are implicitly extended 5893 // up to 64 bits. At the very least, we have to increase the striding of the 5894 // vaargs list to match this, and for FP values we need to introduce 5895 // FP_ROUND nodes as well. 5896 if (VT.isInteger() && !VT.isVector()) 5897 ArgSize = std::max(ArgSize, MinSlotSize); 5898 bool NeedFPTrunc = false; 5899 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) { 5900 ArgSize = 8; 5901 NeedFPTrunc = true; 5902 } 5903 5904 // Increment the pointer, VAList, to the next vaarg 5905 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 5906 DAG.getConstant(ArgSize, DL, PtrVT)); 5907 VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT); 5908 5909 // Store the incremented VAList to the legalized pointer 5910 SDValue APStore = 5911 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V)); 5912 5913 // Load the actual argument out of the pointer VAList 5914 if (NeedFPTrunc) { 5915 // Load the value as an f64. 5916 SDValue WideFP = 5917 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo()); 5918 // Round the value down to an f32. 5919 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0), 5920 DAG.getIntPtrConstant(1, DL)); 5921 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) }; 5922 // Merge the rounded value with the chain output of the load. 5923 return DAG.getMergeValues(Ops, DL); 5924 } 5925 5926 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo()); 5927 } 5928 5929 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op, 5930 SelectionDAG &DAG) const { 5931 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5932 MFI.setFrameAddressIsTaken(true); 5933 5934 EVT VT = Op.getValueType(); 5935 SDLoc DL(Op); 5936 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5937 SDValue FrameAddr = 5938 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64); 5939 while (Depth--) 5940 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr, 5941 MachinePointerInfo()); 5942 5943 if (Subtarget->isTargetILP32()) 5944 FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr, 5945 DAG.getValueType(VT)); 5946 5947 return FrameAddr; 5948 } 5949 5950 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op, 5951 SelectionDAG &DAG) const { 5952 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5953 5954 EVT VT = getPointerTy(DAG.getDataLayout()); 5955 SDLoc DL(Op); 5956 int FI = MFI.CreateFixedObject(4, 0, false); 5957 return DAG.getFrameIndex(FI, VT); 5958 } 5959 5960 #define GET_REGISTER_MATCHER 5961 #include "AArch64GenAsmMatcher.inc" 5962 5963 // FIXME? Maybe this could be a TableGen attribute on some registers and 5964 // this table could be generated automatically from RegInfo. 5965 Register AArch64TargetLowering:: 5966 getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const { 5967 Register Reg = MatchRegisterName(RegName); 5968 if (AArch64::X1 <= Reg && Reg <= AArch64::X28) { 5969 const MCRegisterInfo *MRI = Subtarget->getRegisterInfo(); 5970 unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false); 5971 if (!Subtarget->isXRegisterReserved(DwarfRegNum)) 5972 Reg = 0; 5973 } 5974 if (Reg) 5975 return Reg; 5976 report_fatal_error(Twine("Invalid register name \"" 5977 + StringRef(RegName) + "\".")); 5978 } 5979 5980 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op, 5981 SelectionDAG &DAG) const { 5982 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true); 5983 5984 EVT VT = Op.getValueType(); 5985 SDLoc DL(Op); 5986 5987 SDValue FrameAddr = 5988 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT); 5989 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout())); 5990 5991 return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset); 5992 } 5993 5994 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op, 5995 SelectionDAG &DAG) const { 5996 MachineFunction &MF = DAG.getMachineFunction(); 5997 MachineFrameInfo &MFI = MF.getFrameInfo(); 5998 MFI.setReturnAddressIsTaken(true); 5999 6000 EVT VT = Op.getValueType(); 6001 SDLoc DL(Op); 6002 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 6003 if (Depth) { 6004 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 6005 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout())); 6006 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 6007 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 6008 MachinePointerInfo()); 6009 } 6010 6011 // Return LR, which contains the return address. Mark it an implicit live-in. 6012 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass); 6013 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 6014 } 6015 6016 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 6017 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 6018 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op, 6019 SelectionDAG &DAG) const { 6020 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 6021 EVT VT = Op.getValueType(); 6022 unsigned VTBits = VT.getSizeInBits(); 6023 SDLoc dl(Op); 6024 SDValue ShOpLo = Op.getOperand(0); 6025 SDValue ShOpHi = Op.getOperand(1); 6026 SDValue ShAmt = Op.getOperand(2); 6027 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 6028 6029 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 6030 6031 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 6032 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 6033 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 6034 6035 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which 6036 // is "undef". We wanted 0, so CSEL it directly. 6037 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 6038 ISD::SETEQ, dl, DAG); 6039 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 6040 HiBitsForLo = 6041 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 6042 HiBitsForLo, CCVal, Cmp); 6043 6044 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 6045 DAG.getConstant(VTBits, dl, MVT::i64)); 6046 6047 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 6048 SDValue LoForNormalShift = 6049 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo); 6050 6051 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 6052 dl, DAG); 6053 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 6054 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 6055 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 6056 LoForNormalShift, CCVal, Cmp); 6057 6058 // AArch64 shifts larger than the register width are wrapped rather than 6059 // clamped, so we can't just emit "hi >> x". 6060 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 6061 SDValue HiForBigShift = 6062 Opc == ISD::SRA 6063 ? DAG.getNode(Opc, dl, VT, ShOpHi, 6064 DAG.getConstant(VTBits - 1, dl, MVT::i64)) 6065 : DAG.getConstant(0, dl, VT); 6066 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 6067 HiForNormalShift, CCVal, Cmp); 6068 6069 SDValue Ops[2] = { Lo, Hi }; 6070 return DAG.getMergeValues(Ops, dl); 6071 } 6072 6073 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 6074 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 6075 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op, 6076 SelectionDAG &DAG) const { 6077 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 6078 EVT VT = Op.getValueType(); 6079 unsigned VTBits = VT.getSizeInBits(); 6080 SDLoc dl(Op); 6081 SDValue ShOpLo = Op.getOperand(0); 6082 SDValue ShOpHi = Op.getOperand(1); 6083 SDValue ShAmt = Op.getOperand(2); 6084 6085 assert(Op.getOpcode() == ISD::SHL_PARTS); 6086 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 6087 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 6088 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 6089 6090 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which 6091 // is "undef". We wanted 0, so CSEL it directly. 6092 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 6093 ISD::SETEQ, dl, DAG); 6094 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 6095 LoBitsForHi = 6096 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 6097 LoBitsForHi, CCVal, Cmp); 6098 6099 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 6100 DAG.getConstant(VTBits, dl, MVT::i64)); 6101 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 6102 SDValue HiForNormalShift = 6103 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi); 6104 6105 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 6106 6107 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 6108 dl, DAG); 6109 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 6110 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 6111 HiForNormalShift, CCVal, Cmp); 6112 6113 // AArch64 shifts of larger than register sizes are wrapped rather than 6114 // clamped, so we can't just emit "lo << a" if a is too big. 6115 SDValue LoForBigShift = DAG.getConstant(0, dl, VT); 6116 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 6117 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 6118 LoForNormalShift, CCVal, Cmp); 6119 6120 SDValue Ops[2] = { Lo, Hi }; 6121 return DAG.getMergeValues(Ops, dl); 6122 } 6123 6124 bool AArch64TargetLowering::isOffsetFoldingLegal( 6125 const GlobalAddressSDNode *GA) const { 6126 // Offsets are folded in the DAG combine rather than here so that we can 6127 // intelligently choose an offset based on the uses. 6128 return false; 6129 } 6130 6131 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 6132 bool OptForSize) const { 6133 bool IsLegal = false; 6134 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and 6135 // 16-bit case when target has full fp16 support. 6136 // FIXME: We should be able to handle f128 as well with a clever lowering. 6137 const APInt ImmInt = Imm.bitcastToAPInt(); 6138 if (VT == MVT::f64) 6139 IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero(); 6140 else if (VT == MVT::f32) 6141 IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero(); 6142 else if (VT == MVT::f16 && Subtarget->hasFullFP16()) 6143 IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero(); 6144 // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to 6145 // generate that fmov. 6146 6147 // If we can not materialize in immediate field for fmov, check if the 6148 // value can be encoded as the immediate operand of a logical instruction. 6149 // The immediate value will be created with either MOVZ, MOVN, or ORR. 6150 if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) { 6151 // The cost is actually exactly the same for mov+fmov vs. adrp+ldr; 6152 // however the mov+fmov sequence is always better because of the reduced 6153 // cache pressure. The timings are still the same if you consider 6154 // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the 6155 // movw+movk is fused). So we limit up to 2 instrdduction at most. 6156 SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn; 6157 AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(), 6158 Insn); 6159 unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2)); 6160 IsLegal = Insn.size() <= Limit; 6161 } 6162 6163 LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString() 6164 << " imm value: "; Imm.dump();); 6165 return IsLegal; 6166 } 6167 6168 //===----------------------------------------------------------------------===// 6169 // AArch64 Optimization Hooks 6170 //===----------------------------------------------------------------------===// 6171 6172 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode, 6173 SDValue Operand, SelectionDAG &DAG, 6174 int &ExtraSteps) { 6175 EVT VT = Operand.getValueType(); 6176 if (ST->hasNEON() && 6177 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 || 6178 VT == MVT::f32 || VT == MVT::v1f32 || 6179 VT == MVT::v2f32 || VT == MVT::v4f32)) { 6180 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified) 6181 // For the reciprocal estimates, convergence is quadratic, so the number 6182 // of digits is doubled after each iteration. In ARMv8, the accuracy of 6183 // the initial estimate is 2^-8. Thus the number of extra steps to refine 6184 // the result for float (23 mantissa bits) is 2 and for double (52 6185 // mantissa bits) is 3. 6186 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2; 6187 6188 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand); 6189 } 6190 6191 return SDValue(); 6192 } 6193 6194 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand, 6195 SelectionDAG &DAG, int Enabled, 6196 int &ExtraSteps, 6197 bool &UseOneConst, 6198 bool Reciprocal) const { 6199 if (Enabled == ReciprocalEstimate::Enabled || 6200 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt())) 6201 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand, 6202 DAG, ExtraSteps)) { 6203 SDLoc DL(Operand); 6204 EVT VT = Operand.getValueType(); 6205 6206 SDNodeFlags Flags; 6207 Flags.setAllowReassociation(true); 6208 6209 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2) 6210 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N) 6211 for (int i = ExtraSteps; i > 0; --i) { 6212 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate, 6213 Flags); 6214 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags); 6215 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags); 6216 } 6217 if (!Reciprocal) { 6218 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 6219 VT); 6220 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 6221 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ); 6222 6223 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags); 6224 // Correct the result if the operand is 0.0. 6225 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, 6226 VT, Eq, Operand, Estimate); 6227 } 6228 6229 ExtraSteps = 0; 6230 return Estimate; 6231 } 6232 6233 return SDValue(); 6234 } 6235 6236 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand, 6237 SelectionDAG &DAG, int Enabled, 6238 int &ExtraSteps) const { 6239 if (Enabled == ReciprocalEstimate::Enabled) 6240 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand, 6241 DAG, ExtraSteps)) { 6242 SDLoc DL(Operand); 6243 EVT VT = Operand.getValueType(); 6244 6245 SDNodeFlags Flags; 6246 Flags.setAllowReassociation(true); 6247 6248 // Newton reciprocal iteration: E * (2 - X * E) 6249 // AArch64 reciprocal iteration instruction: (2 - M * N) 6250 for (int i = ExtraSteps; i > 0; --i) { 6251 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand, 6252 Estimate, Flags); 6253 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags); 6254 } 6255 6256 ExtraSteps = 0; 6257 return Estimate; 6258 } 6259 6260 return SDValue(); 6261 } 6262 6263 //===----------------------------------------------------------------------===// 6264 // AArch64 Inline Assembly Support 6265 //===----------------------------------------------------------------------===// 6266 6267 // Table of Constraints 6268 // TODO: This is the current set of constraints supported by ARM for the 6269 // compiler, not all of them may make sense. 6270 // 6271 // r - A general register 6272 // w - An FP/SIMD register of some size in the range v0-v31 6273 // x - An FP/SIMD register of some size in the range v0-v15 6274 // I - Constant that can be used with an ADD instruction 6275 // J - Constant that can be used with a SUB instruction 6276 // K - Constant that can be used with a 32-bit logical instruction 6277 // L - Constant that can be used with a 64-bit logical instruction 6278 // M - Constant that can be used as a 32-bit MOV immediate 6279 // N - Constant that can be used as a 64-bit MOV immediate 6280 // Q - A memory reference with base register and no offset 6281 // S - A symbolic address 6282 // Y - Floating point constant zero 6283 // Z - Integer constant zero 6284 // 6285 // Note that general register operands will be output using their 64-bit x 6286 // register name, whatever the size of the variable, unless the asm operand 6287 // is prefixed by the %w modifier. Floating-point and SIMD register operands 6288 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or 6289 // %q modifier. 6290 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 6291 // At this point, we have to lower this constraint to something else, so we 6292 // lower it to an "r" or "w". However, by doing this we will force the result 6293 // to be in register, while the X constraint is much more permissive. 6294 // 6295 // Although we are correct (we are free to emit anything, without 6296 // constraints), we might break use cases that would expect us to be more 6297 // efficient and emit something else. 6298 if (!Subtarget->hasFPARMv8()) 6299 return "r"; 6300 6301 if (ConstraintVT.isFloatingPoint()) 6302 return "w"; 6303 6304 if (ConstraintVT.isVector() && 6305 (ConstraintVT.getSizeInBits() == 64 || 6306 ConstraintVT.getSizeInBits() == 128)) 6307 return "w"; 6308 6309 return "r"; 6310 } 6311 6312 enum PredicateConstraint { 6313 Upl, 6314 Upa, 6315 Invalid 6316 }; 6317 6318 static PredicateConstraint parsePredicateConstraint(StringRef Constraint) { 6319 PredicateConstraint P = PredicateConstraint::Invalid; 6320 if (Constraint == "Upa") 6321 P = PredicateConstraint::Upa; 6322 if (Constraint == "Upl") 6323 P = PredicateConstraint::Upl; 6324 return P; 6325 } 6326 6327 /// getConstraintType - Given a constraint letter, return the type of 6328 /// constraint it is for this target. 6329 AArch64TargetLowering::ConstraintType 6330 AArch64TargetLowering::getConstraintType(StringRef Constraint) const { 6331 if (Constraint.size() == 1) { 6332 switch (Constraint[0]) { 6333 default: 6334 break; 6335 case 'x': 6336 case 'w': 6337 case 'y': 6338 return C_RegisterClass; 6339 // An address with a single base register. Due to the way we 6340 // currently handle addresses it is the same as 'r'. 6341 case 'Q': 6342 return C_Memory; 6343 case 'I': 6344 case 'J': 6345 case 'K': 6346 case 'L': 6347 case 'M': 6348 case 'N': 6349 case 'Y': 6350 case 'Z': 6351 return C_Immediate; 6352 case 'z': 6353 case 'S': // A symbolic address 6354 return C_Other; 6355 } 6356 } else if (parsePredicateConstraint(Constraint) != 6357 PredicateConstraint::Invalid) 6358 return C_RegisterClass; 6359 return TargetLowering::getConstraintType(Constraint); 6360 } 6361 6362 /// Examine constraint type and operand type and determine a weight value. 6363 /// This object must already have been set up with the operand type 6364 /// and the current alternative constraint selected. 6365 TargetLowering::ConstraintWeight 6366 AArch64TargetLowering::getSingleConstraintMatchWeight( 6367 AsmOperandInfo &info, const char *constraint) const { 6368 ConstraintWeight weight = CW_Invalid; 6369 Value *CallOperandVal = info.CallOperandVal; 6370 // If we don't have a value, we can't do a match, 6371 // but allow it at the lowest weight. 6372 if (!CallOperandVal) 6373 return CW_Default; 6374 Type *type = CallOperandVal->getType(); 6375 // Look at the constraint type. 6376 switch (*constraint) { 6377 default: 6378 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 6379 break; 6380 case 'x': 6381 case 'w': 6382 case 'y': 6383 if (type->isFloatingPointTy() || type->isVectorTy()) 6384 weight = CW_Register; 6385 break; 6386 case 'z': 6387 weight = CW_Constant; 6388 break; 6389 case 'U': 6390 if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid) 6391 weight = CW_Register; 6392 break; 6393 } 6394 return weight; 6395 } 6396 6397 std::pair<unsigned, const TargetRegisterClass *> 6398 AArch64TargetLowering::getRegForInlineAsmConstraint( 6399 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 6400 if (Constraint.size() == 1) { 6401 switch (Constraint[0]) { 6402 case 'r': 6403 if (VT.getSizeInBits() == 64) 6404 return std::make_pair(0U, &AArch64::GPR64commonRegClass); 6405 return std::make_pair(0U, &AArch64::GPR32commonRegClass); 6406 case 'w': 6407 if (!Subtarget->hasFPARMv8()) 6408 break; 6409 if (VT.isScalableVector()) 6410 return std::make_pair(0U, &AArch64::ZPRRegClass); 6411 if (VT.getSizeInBits() == 16) 6412 return std::make_pair(0U, &AArch64::FPR16RegClass); 6413 if (VT.getSizeInBits() == 32) 6414 return std::make_pair(0U, &AArch64::FPR32RegClass); 6415 if (VT.getSizeInBits() == 64) 6416 return std::make_pair(0U, &AArch64::FPR64RegClass); 6417 if (VT.getSizeInBits() == 128) 6418 return std::make_pair(0U, &AArch64::FPR128RegClass); 6419 break; 6420 // The instructions that this constraint is designed for can 6421 // only take 128-bit registers so just use that regclass. 6422 case 'x': 6423 if (!Subtarget->hasFPARMv8()) 6424 break; 6425 if (VT.isScalableVector()) 6426 return std::make_pair(0U, &AArch64::ZPR_4bRegClass); 6427 if (VT.getSizeInBits() == 128) 6428 return std::make_pair(0U, &AArch64::FPR128_loRegClass); 6429 break; 6430 case 'y': 6431 if (!Subtarget->hasFPARMv8()) 6432 break; 6433 if (VT.isScalableVector()) 6434 return std::make_pair(0U, &AArch64::ZPR_3bRegClass); 6435 break; 6436 } 6437 } else { 6438 PredicateConstraint PC = parsePredicateConstraint(Constraint); 6439 if (PC != PredicateConstraint::Invalid) { 6440 assert(VT.isScalableVector()); 6441 bool restricted = (PC == PredicateConstraint::Upl); 6442 return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass) 6443 : std::make_pair(0U, &AArch64::PPRRegClass); 6444 } 6445 } 6446 if (StringRef("{cc}").equals_lower(Constraint)) 6447 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass); 6448 6449 // Use the default implementation in TargetLowering to convert the register 6450 // constraint into a member of a register class. 6451 std::pair<unsigned, const TargetRegisterClass *> Res; 6452 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 6453 6454 // Not found as a standard register? 6455 if (!Res.second) { 6456 unsigned Size = Constraint.size(); 6457 if ((Size == 4 || Size == 5) && Constraint[0] == '{' && 6458 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') { 6459 int RegNo; 6460 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo); 6461 if (!Failed && RegNo >= 0 && RegNo <= 31) { 6462 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size. 6463 // By default we'll emit v0-v31 for this unless there's a modifier where 6464 // we'll emit the correct register as well. 6465 if (VT != MVT::Other && VT.getSizeInBits() == 64) { 6466 Res.first = AArch64::FPR64RegClass.getRegister(RegNo); 6467 Res.second = &AArch64::FPR64RegClass; 6468 } else { 6469 Res.first = AArch64::FPR128RegClass.getRegister(RegNo); 6470 Res.second = &AArch64::FPR128RegClass; 6471 } 6472 } 6473 } 6474 } 6475 6476 if (Res.second && !Subtarget->hasFPARMv8() && 6477 !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) && 6478 !AArch64::GPR64allRegClass.hasSubClassEq(Res.second)) 6479 return std::make_pair(0U, nullptr); 6480 6481 return Res; 6482 } 6483 6484 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 6485 /// vector. If it is invalid, don't add anything to Ops. 6486 void AArch64TargetLowering::LowerAsmOperandForConstraint( 6487 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 6488 SelectionDAG &DAG) const { 6489 SDValue Result; 6490 6491 // Currently only support length 1 constraints. 6492 if (Constraint.length() != 1) 6493 return; 6494 6495 char ConstraintLetter = Constraint[0]; 6496 switch (ConstraintLetter) { 6497 default: 6498 break; 6499 6500 // This set of constraints deal with valid constants for various instructions. 6501 // Validate and return a target constant for them if we can. 6502 case 'z': { 6503 // 'z' maps to xzr or wzr so it needs an input of 0. 6504 if (!isNullConstant(Op)) 6505 return; 6506 6507 if (Op.getValueType() == MVT::i64) 6508 Result = DAG.getRegister(AArch64::XZR, MVT::i64); 6509 else 6510 Result = DAG.getRegister(AArch64::WZR, MVT::i32); 6511 break; 6512 } 6513 case 'S': { 6514 // An absolute symbolic address or label reference. 6515 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 6516 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 6517 GA->getValueType(0)); 6518 } else if (const BlockAddressSDNode *BA = 6519 dyn_cast<BlockAddressSDNode>(Op)) { 6520 Result = 6521 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0)); 6522 } else if (const ExternalSymbolSDNode *ES = 6523 dyn_cast<ExternalSymbolSDNode>(Op)) { 6524 Result = 6525 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0)); 6526 } else 6527 return; 6528 break; 6529 } 6530 6531 case 'I': 6532 case 'J': 6533 case 'K': 6534 case 'L': 6535 case 'M': 6536 case 'N': 6537 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 6538 if (!C) 6539 return; 6540 6541 // Grab the value and do some validation. 6542 uint64_t CVal = C->getZExtValue(); 6543 switch (ConstraintLetter) { 6544 // The I constraint applies only to simple ADD or SUB immediate operands: 6545 // i.e. 0 to 4095 with optional shift by 12 6546 // The J constraint applies only to ADD or SUB immediates that would be 6547 // valid when negated, i.e. if [an add pattern] were to be output as a SUB 6548 // instruction [or vice versa], in other words -1 to -4095 with optional 6549 // left shift by 12. 6550 case 'I': 6551 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal)) 6552 break; 6553 return; 6554 case 'J': { 6555 uint64_t NVal = -C->getSExtValue(); 6556 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) { 6557 CVal = C->getSExtValue(); 6558 break; 6559 } 6560 return; 6561 } 6562 // The K and L constraints apply *only* to logical immediates, including 6563 // what used to be the MOVI alias for ORR (though the MOVI alias has now 6564 // been removed and MOV should be used). So these constraints have to 6565 // distinguish between bit patterns that are valid 32-bit or 64-bit 6566 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but 6567 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice 6568 // versa. 6569 case 'K': 6570 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 6571 break; 6572 return; 6573 case 'L': 6574 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 6575 break; 6576 return; 6577 // The M and N constraints are a superset of K and L respectively, for use 6578 // with the MOV (immediate) alias. As well as the logical immediates they 6579 // also match 32 or 64-bit immediates that can be loaded either using a 6580 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca 6581 // (M) or 64-bit 0x1234000000000000 (N) etc. 6582 // As a note some of this code is liberally stolen from the asm parser. 6583 case 'M': { 6584 if (!isUInt<32>(CVal)) 6585 return; 6586 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 6587 break; 6588 if ((CVal & 0xFFFF) == CVal) 6589 break; 6590 if ((CVal & 0xFFFF0000ULL) == CVal) 6591 break; 6592 uint64_t NCVal = ~(uint32_t)CVal; 6593 if ((NCVal & 0xFFFFULL) == NCVal) 6594 break; 6595 if ((NCVal & 0xFFFF0000ULL) == NCVal) 6596 break; 6597 return; 6598 } 6599 case 'N': { 6600 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 6601 break; 6602 if ((CVal & 0xFFFFULL) == CVal) 6603 break; 6604 if ((CVal & 0xFFFF0000ULL) == CVal) 6605 break; 6606 if ((CVal & 0xFFFF00000000ULL) == CVal) 6607 break; 6608 if ((CVal & 0xFFFF000000000000ULL) == CVal) 6609 break; 6610 uint64_t NCVal = ~CVal; 6611 if ((NCVal & 0xFFFFULL) == NCVal) 6612 break; 6613 if ((NCVal & 0xFFFF0000ULL) == NCVal) 6614 break; 6615 if ((NCVal & 0xFFFF00000000ULL) == NCVal) 6616 break; 6617 if ((NCVal & 0xFFFF000000000000ULL) == NCVal) 6618 break; 6619 return; 6620 } 6621 default: 6622 return; 6623 } 6624 6625 // All assembler immediates are 64-bit integers. 6626 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64); 6627 break; 6628 } 6629 6630 if (Result.getNode()) { 6631 Ops.push_back(Result); 6632 return; 6633 } 6634 6635 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 6636 } 6637 6638 //===----------------------------------------------------------------------===// 6639 // AArch64 Advanced SIMD Support 6640 //===----------------------------------------------------------------------===// 6641 6642 /// WidenVector - Given a value in the V64 register class, produce the 6643 /// equivalent value in the V128 register class. 6644 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) { 6645 EVT VT = V64Reg.getValueType(); 6646 unsigned NarrowSize = VT.getVectorNumElements(); 6647 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 6648 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize); 6649 SDLoc DL(V64Reg); 6650 6651 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy), 6652 V64Reg, DAG.getConstant(0, DL, MVT::i32)); 6653 } 6654 6655 /// getExtFactor - Determine the adjustment factor for the position when 6656 /// generating an "extract from vector registers" instruction. 6657 static unsigned getExtFactor(SDValue &V) { 6658 EVT EltType = V.getValueType().getVectorElementType(); 6659 return EltType.getSizeInBits() / 8; 6660 } 6661 6662 /// NarrowVector - Given a value in the V128 register class, produce the 6663 /// equivalent value in the V64 register class. 6664 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) { 6665 EVT VT = V128Reg.getValueType(); 6666 unsigned WideSize = VT.getVectorNumElements(); 6667 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 6668 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2); 6669 SDLoc DL(V128Reg); 6670 6671 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg); 6672 } 6673 6674 // Gather data to see if the operation can be modelled as a 6675 // shuffle in combination with VEXTs. 6676 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op, 6677 SelectionDAG &DAG) const { 6678 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6679 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n"); 6680 SDLoc dl(Op); 6681 EVT VT = Op.getValueType(); 6682 unsigned NumElts = VT.getVectorNumElements(); 6683 6684 struct ShuffleSourceInfo { 6685 SDValue Vec; 6686 unsigned MinElt; 6687 unsigned MaxElt; 6688 6689 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 6690 // be compatible with the shuffle we intend to construct. As a result 6691 // ShuffleVec will be some sliding window into the original Vec. 6692 SDValue ShuffleVec; 6693 6694 // Code should guarantee that element i in Vec starts at element "WindowBase 6695 // + i * WindowScale in ShuffleVec". 6696 int WindowBase; 6697 int WindowScale; 6698 6699 ShuffleSourceInfo(SDValue Vec) 6700 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0), 6701 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {} 6702 6703 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 6704 }; 6705 6706 // First gather all vectors used as an immediate source for this BUILD_VECTOR 6707 // node. 6708 SmallVector<ShuffleSourceInfo, 2> Sources; 6709 for (unsigned i = 0; i < NumElts; ++i) { 6710 SDValue V = Op.getOperand(i); 6711 if (V.isUndef()) 6712 continue; 6713 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 6714 !isa<ConstantSDNode>(V.getOperand(1))) { 6715 LLVM_DEBUG( 6716 dbgs() << "Reshuffle failed: " 6717 "a shuffle can only come from building a vector from " 6718 "various elements of other vectors, provided their " 6719 "indices are constant\n"); 6720 return SDValue(); 6721 } 6722 6723 // Add this element source to the list if it's not already there. 6724 SDValue SourceVec = V.getOperand(0); 6725 auto Source = find(Sources, SourceVec); 6726 if (Source == Sources.end()) 6727 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 6728 6729 // Update the minimum and maximum lane number seen. 6730 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 6731 Source->MinElt = std::min(Source->MinElt, EltNo); 6732 Source->MaxElt = std::max(Source->MaxElt, EltNo); 6733 } 6734 6735 if (Sources.size() > 2) { 6736 LLVM_DEBUG( 6737 dbgs() << "Reshuffle failed: currently only do something sane when at " 6738 "most two source vectors are involved\n"); 6739 return SDValue(); 6740 } 6741 6742 // Find out the smallest element size among result and two sources, and use 6743 // it as element size to build the shuffle_vector. 6744 EVT SmallestEltTy = VT.getVectorElementType(); 6745 for (auto &Source : Sources) { 6746 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 6747 if (SrcEltTy.bitsLT(SmallestEltTy)) { 6748 SmallestEltTy = SrcEltTy; 6749 } 6750 } 6751 unsigned ResMultiplier = 6752 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 6753 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6754 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 6755 6756 // If the source vector is too wide or too narrow, we may nevertheless be able 6757 // to construct a compatible shuffle either by concatenating it with UNDEF or 6758 // extracting a suitable range of elements. 6759 for (auto &Src : Sources) { 6760 EVT SrcVT = Src.ShuffleVec.getValueType(); 6761 6762 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 6763 continue; 6764 6765 // This stage of the search produces a source with the same element type as 6766 // the original, but with a total width matching the BUILD_VECTOR output. 6767 EVT EltVT = SrcVT.getVectorElementType(); 6768 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 6769 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 6770 6771 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 6772 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits()); 6773 // We can pad out the smaller vector for free, so if it's part of a 6774 // shuffle... 6775 Src.ShuffleVec = 6776 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 6777 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 6778 continue; 6779 } 6780 6781 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits()); 6782 6783 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 6784 LLVM_DEBUG( 6785 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n"); 6786 return SDValue(); 6787 } 6788 6789 if (Src.MinElt >= NumSrcElts) { 6790 // The extraction can just take the second half 6791 Src.ShuffleVec = 6792 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6793 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 6794 Src.WindowBase = -NumSrcElts; 6795 } else if (Src.MaxElt < NumSrcElts) { 6796 // The extraction can just take the first half 6797 Src.ShuffleVec = 6798 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6799 DAG.getConstant(0, dl, MVT::i64)); 6800 } else { 6801 // An actual VEXT is needed 6802 SDValue VEXTSrc1 = 6803 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6804 DAG.getConstant(0, dl, MVT::i64)); 6805 SDValue VEXTSrc2 = 6806 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6807 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 6808 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1); 6809 6810 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1, 6811 VEXTSrc2, 6812 DAG.getConstant(Imm, dl, MVT::i32)); 6813 Src.WindowBase = -Src.MinElt; 6814 } 6815 } 6816 6817 // Another possible incompatibility occurs from the vector element types. We 6818 // can fix this by bitcasting the source vectors to the same type we intend 6819 // for the shuffle. 6820 for (auto &Src : Sources) { 6821 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 6822 if (SrcEltTy == SmallestEltTy) 6823 continue; 6824 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 6825 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 6826 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6827 Src.WindowBase *= Src.WindowScale; 6828 } 6829 6830 // Final sanity check before we try to actually produce a shuffle. 6831 LLVM_DEBUG(for (auto Src 6832 : Sources) 6833 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 6834 6835 // The stars all align, our next step is to produce the mask for the shuffle. 6836 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6837 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 6838 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6839 SDValue Entry = Op.getOperand(i); 6840 if (Entry.isUndef()) 6841 continue; 6842 6843 auto Src = find(Sources, Entry.getOperand(0)); 6844 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6845 6846 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6847 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6848 // segment. 6849 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6850 int BitsDefined = 6851 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits()); 6852 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6853 6854 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6855 // starting at the appropriate offset. 6856 int *LaneMask = &Mask[i * ResMultiplier]; 6857 6858 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6859 ExtractBase += NumElts * (Src - Sources.begin()); 6860 for (int j = 0; j < LanesDefined; ++j) 6861 LaneMask[j] = ExtractBase + j; 6862 } 6863 6864 // Final check before we try to produce nonsense... 6865 if (!isShuffleMaskLegal(Mask, ShuffleVT)) { 6866 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n"); 6867 return SDValue(); 6868 } 6869 6870 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6871 for (unsigned i = 0; i < Sources.size(); ++i) 6872 ShuffleOps[i] = Sources[i].ShuffleVec; 6873 6874 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6875 ShuffleOps[1], Mask); 6876 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6877 6878 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump(); 6879 dbgs() << "Reshuffle, creating node: "; V.dump();); 6880 6881 return V; 6882 } 6883 6884 // check if an EXT instruction can handle the shuffle mask when the 6885 // vector sources of the shuffle are the same. 6886 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 6887 unsigned NumElts = VT.getVectorNumElements(); 6888 6889 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6890 if (M[0] < 0) 6891 return false; 6892 6893 Imm = M[0]; 6894 6895 // If this is a VEXT shuffle, the immediate value is the index of the first 6896 // element. The other shuffle indices must be the successive elements after 6897 // the first one. 6898 unsigned ExpectedElt = Imm; 6899 for (unsigned i = 1; i < NumElts; ++i) { 6900 // Increment the expected index. If it wraps around, just follow it 6901 // back to index zero and keep going. 6902 ++ExpectedElt; 6903 if (ExpectedElt == NumElts) 6904 ExpectedElt = 0; 6905 6906 if (M[i] < 0) 6907 continue; // ignore UNDEF indices 6908 if (ExpectedElt != static_cast<unsigned>(M[i])) 6909 return false; 6910 } 6911 6912 return true; 6913 } 6914 6915 // check if an EXT instruction can handle the shuffle mask when the 6916 // vector sources of the shuffle are different. 6917 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT, 6918 unsigned &Imm) { 6919 // Look for the first non-undef element. 6920 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; }); 6921 6922 // Benefit form APInt to handle overflow when calculating expected element. 6923 unsigned NumElts = VT.getVectorNumElements(); 6924 unsigned MaskBits = APInt(32, NumElts * 2).logBase2(); 6925 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1); 6926 // The following shuffle indices must be the successive elements after the 6927 // first real element. 6928 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(), 6929 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;}); 6930 if (FirstWrongElt != M.end()) 6931 return false; 6932 6933 // The index of an EXT is the first element if it is not UNDEF. 6934 // Watch out for the beginning UNDEFs. The EXT index should be the expected 6935 // value of the first element. E.g. 6936 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>. 6937 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>. 6938 // ExpectedElt is the last mask index plus 1. 6939 Imm = ExpectedElt.getZExtValue(); 6940 6941 // There are two difference cases requiring to reverse input vectors. 6942 // For example, for vector <4 x i32> we have the following cases, 6943 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>) 6944 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>) 6945 // For both cases, we finally use mask <5, 6, 7, 0>, which requires 6946 // to reverse two input vectors. 6947 if (Imm < NumElts) 6948 ReverseEXT = true; 6949 else 6950 Imm -= NumElts; 6951 6952 return true; 6953 } 6954 6955 /// isREVMask - Check if a vector shuffle corresponds to a REV 6956 /// instruction with the specified blocksize. (The order of the elements 6957 /// within each block of the vector is reversed.) 6958 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 6959 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) && 6960 "Only possible block sizes for REV are: 16, 32, 64"); 6961 6962 unsigned EltSz = VT.getScalarSizeInBits(); 6963 if (EltSz == 64) 6964 return false; 6965 6966 unsigned NumElts = VT.getVectorNumElements(); 6967 unsigned BlockElts = M[0] + 1; 6968 // If the first shuffle index is UNDEF, be optimistic. 6969 if (M[0] < 0) 6970 BlockElts = BlockSize / EltSz; 6971 6972 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 6973 return false; 6974 6975 for (unsigned i = 0; i < NumElts; ++i) { 6976 if (M[i] < 0) 6977 continue; // ignore UNDEF indices 6978 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts)) 6979 return false; 6980 } 6981 6982 return true; 6983 } 6984 6985 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6986 unsigned NumElts = VT.getVectorNumElements(); 6987 if (NumElts % 2 != 0) 6988 return false; 6989 WhichResult = (M[0] == 0 ? 0 : 1); 6990 unsigned Idx = WhichResult * NumElts / 2; 6991 for (unsigned i = 0; i != NumElts; i += 2) { 6992 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 6993 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts)) 6994 return false; 6995 Idx += 1; 6996 } 6997 6998 return true; 6999 } 7000 7001 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7002 unsigned NumElts = VT.getVectorNumElements(); 7003 WhichResult = (M[0] == 0 ? 0 : 1); 7004 for (unsigned i = 0; i != NumElts; ++i) { 7005 if (M[i] < 0) 7006 continue; // ignore UNDEF indices 7007 if ((unsigned)M[i] != 2 * i + WhichResult) 7008 return false; 7009 } 7010 7011 return true; 7012 } 7013 7014 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7015 unsigned NumElts = VT.getVectorNumElements(); 7016 if (NumElts % 2 != 0) 7017 return false; 7018 WhichResult = (M[0] == 0 ? 0 : 1); 7019 for (unsigned i = 0; i < NumElts; i += 2) { 7020 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 7021 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult)) 7022 return false; 7023 } 7024 return true; 7025 } 7026 7027 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of 7028 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 7029 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 7030 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7031 unsigned NumElts = VT.getVectorNumElements(); 7032 if (NumElts % 2 != 0) 7033 return false; 7034 WhichResult = (M[0] == 0 ? 0 : 1); 7035 unsigned Idx = WhichResult * NumElts / 2; 7036 for (unsigned i = 0; i != NumElts; i += 2) { 7037 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 7038 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx)) 7039 return false; 7040 Idx += 1; 7041 } 7042 7043 return true; 7044 } 7045 7046 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of 7047 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 7048 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 7049 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7050 unsigned Half = VT.getVectorNumElements() / 2; 7051 WhichResult = (M[0] == 0 ? 0 : 1); 7052 for (unsigned j = 0; j != 2; ++j) { 7053 unsigned Idx = WhichResult; 7054 for (unsigned i = 0; i != Half; ++i) { 7055 int MIdx = M[i + j * Half]; 7056 if (MIdx >= 0 && (unsigned)MIdx != Idx) 7057 return false; 7058 Idx += 2; 7059 } 7060 } 7061 7062 return true; 7063 } 7064 7065 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of 7066 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 7067 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 7068 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 7069 unsigned NumElts = VT.getVectorNumElements(); 7070 if (NumElts % 2 != 0) 7071 return false; 7072 WhichResult = (M[0] == 0 ? 0 : 1); 7073 for (unsigned i = 0; i < NumElts; i += 2) { 7074 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 7075 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult)) 7076 return false; 7077 } 7078 return true; 7079 } 7080 7081 static bool isINSMask(ArrayRef<int> M, int NumInputElements, 7082 bool &DstIsLeft, int &Anomaly) { 7083 if (M.size() != static_cast<size_t>(NumInputElements)) 7084 return false; 7085 7086 int NumLHSMatch = 0, NumRHSMatch = 0; 7087 int LastLHSMismatch = -1, LastRHSMismatch = -1; 7088 7089 for (int i = 0; i < NumInputElements; ++i) { 7090 if (M[i] == -1) { 7091 ++NumLHSMatch; 7092 ++NumRHSMatch; 7093 continue; 7094 } 7095 7096 if (M[i] == i) 7097 ++NumLHSMatch; 7098 else 7099 LastLHSMismatch = i; 7100 7101 if (M[i] == i + NumInputElements) 7102 ++NumRHSMatch; 7103 else 7104 LastRHSMismatch = i; 7105 } 7106 7107 if (NumLHSMatch == NumInputElements - 1) { 7108 DstIsLeft = true; 7109 Anomaly = LastLHSMismatch; 7110 return true; 7111 } else if (NumRHSMatch == NumInputElements - 1) { 7112 DstIsLeft = false; 7113 Anomaly = LastRHSMismatch; 7114 return true; 7115 } 7116 7117 return false; 7118 } 7119 7120 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) { 7121 if (VT.getSizeInBits() != 128) 7122 return false; 7123 7124 unsigned NumElts = VT.getVectorNumElements(); 7125 7126 for (int I = 0, E = NumElts / 2; I != E; I++) { 7127 if (Mask[I] != I) 7128 return false; 7129 } 7130 7131 int Offset = NumElts / 2; 7132 for (int I = NumElts / 2, E = NumElts; I != E; I++) { 7133 if (Mask[I] != I + SplitLHS * Offset) 7134 return false; 7135 } 7136 7137 return true; 7138 } 7139 7140 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) { 7141 SDLoc DL(Op); 7142 EVT VT = Op.getValueType(); 7143 SDValue V0 = Op.getOperand(0); 7144 SDValue V1 = Op.getOperand(1); 7145 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask(); 7146 7147 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() || 7148 VT.getVectorElementType() != V1.getValueType().getVectorElementType()) 7149 return SDValue(); 7150 7151 bool SplitV0 = V0.getValueSizeInBits() == 128; 7152 7153 if (!isConcatMask(Mask, VT, SplitV0)) 7154 return SDValue(); 7155 7156 EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 7157 if (SplitV0) { 7158 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0, 7159 DAG.getConstant(0, DL, MVT::i64)); 7160 } 7161 if (V1.getValueSizeInBits() == 128) { 7162 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1, 7163 DAG.getConstant(0, DL, MVT::i64)); 7164 } 7165 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1); 7166 } 7167 7168 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 7169 /// the specified operations to build the shuffle. 7170 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 7171 SDValue RHS, SelectionDAG &DAG, 7172 const SDLoc &dl) { 7173 unsigned OpNum = (PFEntry >> 26) & 0x0F; 7174 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1); 7175 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1); 7176 7177 enum { 7178 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 7179 OP_VREV, 7180 OP_VDUP0, 7181 OP_VDUP1, 7182 OP_VDUP2, 7183 OP_VDUP3, 7184 OP_VEXT1, 7185 OP_VEXT2, 7186 OP_VEXT3, 7187 OP_VUZPL, // VUZP, left result 7188 OP_VUZPR, // VUZP, right result 7189 OP_VZIPL, // VZIP, left result 7190 OP_VZIPR, // VZIP, right result 7191 OP_VTRNL, // VTRN, left result 7192 OP_VTRNR // VTRN, right result 7193 }; 7194 7195 if (OpNum == OP_COPY) { 7196 if (LHSID == (1 * 9 + 2) * 9 + 3) 7197 return LHS; 7198 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!"); 7199 return RHS; 7200 } 7201 7202 SDValue OpLHS, OpRHS; 7203 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 7204 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 7205 EVT VT = OpLHS.getValueType(); 7206 7207 switch (OpNum) { 7208 default: 7209 llvm_unreachable("Unknown shuffle opcode!"); 7210 case OP_VREV: 7211 // VREV divides the vector in half and swaps within the half. 7212 if (VT.getVectorElementType() == MVT::i32 || 7213 VT.getVectorElementType() == MVT::f32) 7214 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS); 7215 // vrev <4 x i16> -> REV32 7216 if (VT.getVectorElementType() == MVT::i16 || 7217 VT.getVectorElementType() == MVT::f16) 7218 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS); 7219 // vrev <4 x i8> -> REV16 7220 assert(VT.getVectorElementType() == MVT::i8); 7221 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS); 7222 case OP_VDUP0: 7223 case OP_VDUP1: 7224 case OP_VDUP2: 7225 case OP_VDUP3: { 7226 EVT EltTy = VT.getVectorElementType(); 7227 unsigned Opcode; 7228 if (EltTy == MVT::i8) 7229 Opcode = AArch64ISD::DUPLANE8; 7230 else if (EltTy == MVT::i16 || EltTy == MVT::f16) 7231 Opcode = AArch64ISD::DUPLANE16; 7232 else if (EltTy == MVT::i32 || EltTy == MVT::f32) 7233 Opcode = AArch64ISD::DUPLANE32; 7234 else if (EltTy == MVT::i64 || EltTy == MVT::f64) 7235 Opcode = AArch64ISD::DUPLANE64; 7236 else 7237 llvm_unreachable("Invalid vector element type?"); 7238 7239 if (VT.getSizeInBits() == 64) 7240 OpLHS = WidenVector(OpLHS, DAG); 7241 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64); 7242 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane); 7243 } 7244 case OP_VEXT1: 7245 case OP_VEXT2: 7246 case OP_VEXT3: { 7247 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS); 7248 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS, 7249 DAG.getConstant(Imm, dl, MVT::i32)); 7250 } 7251 case OP_VUZPL: 7252 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, 7253 OpRHS); 7254 case OP_VUZPR: 7255 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, 7256 OpRHS); 7257 case OP_VZIPL: 7258 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, 7259 OpRHS); 7260 case OP_VZIPR: 7261 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, 7262 OpRHS); 7263 case OP_VTRNL: 7264 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, 7265 OpRHS); 7266 case OP_VTRNR: 7267 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, 7268 OpRHS); 7269 } 7270 } 7271 7272 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask, 7273 SelectionDAG &DAG) { 7274 // Check to see if we can use the TBL instruction. 7275 SDValue V1 = Op.getOperand(0); 7276 SDValue V2 = Op.getOperand(1); 7277 SDLoc DL(Op); 7278 7279 EVT EltVT = Op.getValueType().getVectorElementType(); 7280 unsigned BytesPerElt = EltVT.getSizeInBits() / 8; 7281 7282 SmallVector<SDValue, 8> TBLMask; 7283 for (int Val : ShuffleMask) { 7284 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) { 7285 unsigned Offset = Byte + Val * BytesPerElt; 7286 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32)); 7287 } 7288 } 7289 7290 MVT IndexVT = MVT::v8i8; 7291 unsigned IndexLen = 8; 7292 if (Op.getValueSizeInBits() == 128) { 7293 IndexVT = MVT::v16i8; 7294 IndexLen = 16; 7295 } 7296 7297 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1); 7298 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2); 7299 7300 SDValue Shuffle; 7301 if (V2.getNode()->isUndef()) { 7302 if (IndexLen == 8) 7303 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst); 7304 Shuffle = DAG.getNode( 7305 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 7306 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 7307 DAG.getBuildVector(IndexVT, DL, 7308 makeArrayRef(TBLMask.data(), IndexLen))); 7309 } else { 7310 if (IndexLen == 8) { 7311 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst); 7312 Shuffle = DAG.getNode( 7313 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 7314 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 7315 DAG.getBuildVector(IndexVT, DL, 7316 makeArrayRef(TBLMask.data(), IndexLen))); 7317 } else { 7318 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we 7319 // cannot currently represent the register constraints on the input 7320 // table registers. 7321 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst, 7322 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0], 7323 // IndexLen)); 7324 Shuffle = DAG.getNode( 7325 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 7326 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst, 7327 V2Cst, DAG.getBuildVector(IndexVT, DL, 7328 makeArrayRef(TBLMask.data(), IndexLen))); 7329 } 7330 } 7331 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle); 7332 } 7333 7334 static unsigned getDUPLANEOp(EVT EltType) { 7335 if (EltType == MVT::i8) 7336 return AArch64ISD::DUPLANE8; 7337 if (EltType == MVT::i16 || EltType == MVT::f16) 7338 return AArch64ISD::DUPLANE16; 7339 if (EltType == MVT::i32 || EltType == MVT::f32) 7340 return AArch64ISD::DUPLANE32; 7341 if (EltType == MVT::i64 || EltType == MVT::f64) 7342 return AArch64ISD::DUPLANE64; 7343 7344 llvm_unreachable("Invalid vector element type?"); 7345 } 7346 7347 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 7348 SelectionDAG &DAG) const { 7349 SDLoc dl(Op); 7350 EVT VT = Op.getValueType(); 7351 7352 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 7353 7354 // Convert shuffles that are directly supported on NEON to target-specific 7355 // DAG nodes, instead of keeping them as shuffles and matching them again 7356 // during code selection. This is more efficient and avoids the possibility 7357 // of inconsistencies between legalization and selection. 7358 ArrayRef<int> ShuffleMask = SVN->getMask(); 7359 7360 SDValue V1 = Op.getOperand(0); 7361 SDValue V2 = Op.getOperand(1); 7362 7363 if (SVN->isSplat()) { 7364 int Lane = SVN->getSplatIndex(); 7365 // If this is undef splat, generate it via "just" vdup, if possible. 7366 if (Lane == -1) 7367 Lane = 0; 7368 7369 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) 7370 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(), 7371 V1.getOperand(0)); 7372 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non- 7373 // constant. If so, we can just reference the lane's definition directly. 7374 if (V1.getOpcode() == ISD::BUILD_VECTOR && 7375 !isa<ConstantSDNode>(V1.getOperand(Lane))) 7376 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane)); 7377 7378 // Otherwise, duplicate from the lane of the input vector. 7379 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType()); 7380 7381 // Try to eliminate a bitcasted extract subvector before a DUPLANE. 7382 auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) { 7383 // Match: dup (bitcast (extract_subv X, C)), LaneC 7384 if (BitCast.getOpcode() != ISD::BITCAST || 7385 BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR) 7386 return false; 7387 7388 // The extract index must align in the destination type. That may not 7389 // happen if the bitcast is from narrow to wide type. 7390 SDValue Extract = BitCast.getOperand(0); 7391 unsigned ExtIdx = Extract.getConstantOperandVal(1); 7392 unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits(); 7393 unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth; 7394 unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits(); 7395 if (ExtIdxInBits % CastedEltBitWidth != 0) 7396 return false; 7397 7398 // Update the lane value by offsetting with the scaled extract index. 7399 LaneC += ExtIdxInBits / CastedEltBitWidth; 7400 7401 // Determine the casted vector type of the wide vector input. 7402 // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC' 7403 // Examples: 7404 // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3 7405 // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5 7406 unsigned SrcVecNumElts = 7407 Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth; 7408 CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(), 7409 SrcVecNumElts); 7410 return true; 7411 }; 7412 MVT CastVT; 7413 if (getScaledOffsetDup(V1, Lane, CastVT)) { 7414 V1 = DAG.getBitcast(CastVT, V1.getOperand(0).getOperand(0)); 7415 } else if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) { 7416 // The lane is incremented by the index of the extract. 7417 // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3 7418 Lane += V1.getConstantOperandVal(1); 7419 V1 = V1.getOperand(0); 7420 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) { 7421 // The lane is decremented if we are splatting from the 2nd operand. 7422 // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1 7423 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2; 7424 Lane -= Idx * VT.getVectorNumElements() / 2; 7425 V1 = WidenVector(V1.getOperand(Idx), DAG); 7426 } else if (VT.getSizeInBits() == 64) { 7427 // Widen the operand to 128-bit register with undef. 7428 V1 = WidenVector(V1, DAG); 7429 } 7430 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64)); 7431 } 7432 7433 if (isREVMask(ShuffleMask, VT, 64)) 7434 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2); 7435 if (isREVMask(ShuffleMask, VT, 32)) 7436 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2); 7437 if (isREVMask(ShuffleMask, VT, 16)) 7438 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2); 7439 7440 bool ReverseEXT = false; 7441 unsigned Imm; 7442 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) { 7443 if (ReverseEXT) 7444 std::swap(V1, V2); 7445 Imm *= getExtFactor(V1); 7446 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2, 7447 DAG.getConstant(Imm, dl, MVT::i32)); 7448 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) { 7449 Imm *= getExtFactor(V1); 7450 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1, 7451 DAG.getConstant(Imm, dl, MVT::i32)); 7452 } 7453 7454 unsigned WhichResult; 7455 if (isZIPMask(ShuffleMask, VT, WhichResult)) { 7456 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 7457 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 7458 } 7459 if (isUZPMask(ShuffleMask, VT, WhichResult)) { 7460 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 7461 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 7462 } 7463 if (isTRNMask(ShuffleMask, VT, WhichResult)) { 7464 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 7465 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 7466 } 7467 7468 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 7469 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 7470 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 7471 } 7472 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 7473 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 7474 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 7475 } 7476 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 7477 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 7478 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 7479 } 7480 7481 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG)) 7482 return Concat; 7483 7484 bool DstIsLeft; 7485 int Anomaly; 7486 int NumInputElements = V1.getValueType().getVectorNumElements(); 7487 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) { 7488 SDValue DstVec = DstIsLeft ? V1 : V2; 7489 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64); 7490 7491 SDValue SrcVec = V1; 7492 int SrcLane = ShuffleMask[Anomaly]; 7493 if (SrcLane >= NumInputElements) { 7494 SrcVec = V2; 7495 SrcLane -= VT.getVectorNumElements(); 7496 } 7497 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64); 7498 7499 EVT ScalarVT = VT.getVectorElementType(); 7500 7501 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger()) 7502 ScalarVT = MVT::i32; 7503 7504 return DAG.getNode( 7505 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec, 7506 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV), 7507 DstLaneV); 7508 } 7509 7510 // If the shuffle is not directly supported and it has 4 elements, use 7511 // the PerfectShuffle-generated table to synthesize it from other shuffles. 7512 unsigned NumElts = VT.getVectorNumElements(); 7513 if (NumElts == 4) { 7514 unsigned PFIndexes[4]; 7515 for (unsigned i = 0; i != 4; ++i) { 7516 if (ShuffleMask[i] < 0) 7517 PFIndexes[i] = 8; 7518 else 7519 PFIndexes[i] = ShuffleMask[i]; 7520 } 7521 7522 // Compute the index in the perfect shuffle table. 7523 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 7524 PFIndexes[2] * 9 + PFIndexes[3]; 7525 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7526 unsigned Cost = (PFEntry >> 30); 7527 7528 if (Cost <= 4) 7529 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 7530 } 7531 7532 return GenerateTBL(Op, ShuffleMask, DAG); 7533 } 7534 7535 SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op, 7536 SelectionDAG &DAG) const { 7537 SDLoc dl(Op); 7538 EVT VT = Op.getValueType(); 7539 EVT ElemVT = VT.getScalarType(); 7540 7541 SDValue SplatVal = Op.getOperand(0); 7542 7543 // Extend input splat value where needed to fit into a GPR (32b or 64b only) 7544 // FPRs don't have this restriction. 7545 switch (ElemVT.getSimpleVT().SimpleTy) { 7546 case MVT::i1: { 7547 // The general case of i1. There isn't any natural way to do this, 7548 // so we use some trickery with whilelo. 7549 // TODO: Add special cases for splat of constant true/false. 7550 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64); 7551 SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i64, SplatVal, 7552 DAG.getValueType(MVT::i1)); 7553 SDValue ID = DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl, 7554 MVT::i64); 7555 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, ID, 7556 DAG.getConstant(0, dl, MVT::i64), SplatVal); 7557 } 7558 case MVT::i8: 7559 case MVT::i16: 7560 case MVT::i32: 7561 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32); 7562 break; 7563 case MVT::i64: 7564 SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64); 7565 break; 7566 case MVT::f16: 7567 case MVT::f32: 7568 case MVT::f64: 7569 // Fine as is 7570 break; 7571 default: 7572 report_fatal_error("Unsupported SPLAT_VECTOR input operand type"); 7573 } 7574 7575 return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal); 7576 } 7577 7578 SDValue AArch64TargetLowering::LowerDUPQLane(SDValue Op, 7579 SelectionDAG &DAG) const { 7580 SDLoc DL(Op); 7581 7582 EVT VT = Op.getValueType(); 7583 if (!isTypeLegal(VT) || !VT.isScalableVector()) 7584 return SDValue(); 7585 7586 // Current lowering only supports the SVE-ACLE types. 7587 if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock) 7588 return SDValue(); 7589 7590 // The DUPQ operation is indepedent of element type so normalise to i64s. 7591 SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::nxv2i64, Op.getOperand(1)); 7592 SDValue Idx128 = Op.getOperand(2); 7593 7594 // DUPQ can be used when idx is in range. 7595 auto *CIdx = dyn_cast<ConstantSDNode>(Idx128); 7596 if (CIdx && (CIdx->getZExtValue() <= 3)) { 7597 SDValue CI = DAG.getTargetConstant(CIdx->getZExtValue(), DL, MVT::i64); 7598 SDNode *DUPQ = 7599 DAG.getMachineNode(AArch64::DUP_ZZI_Q, DL, MVT::nxv2i64, V, CI); 7600 return DAG.getNode(ISD::BITCAST, DL, VT, SDValue(DUPQ, 0)); 7601 } 7602 7603 // The ACLE says this must produce the same result as: 7604 // svtbl(data, svadd_x(svptrue_b64(), 7605 // svand_x(svptrue_b64(), svindex_u64(0, 1), 1), 7606 // index * 2)) 7607 SDValue One = DAG.getConstant(1, DL, MVT::i64); 7608 SDValue SplatOne = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, One); 7609 7610 // create the vector 0,1,0,1,... 7611 SDValue Zero = DAG.getConstant(0, DL, MVT::i64); 7612 SDValue SV = DAG.getNode(AArch64ISD::INDEX_VECTOR, 7613 DL, MVT::nxv2i64, Zero, One); 7614 SV = DAG.getNode(ISD::AND, DL, MVT::nxv2i64, SV, SplatOne); 7615 7616 // create the vector idx64,idx64+1,idx64,idx64+1,... 7617 SDValue Idx64 = DAG.getNode(ISD::ADD, DL, MVT::i64, Idx128, Idx128); 7618 SDValue SplatIdx64 = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Idx64); 7619 SDValue ShuffleMask = DAG.getNode(ISD::ADD, DL, MVT::nxv2i64, SV, SplatIdx64); 7620 7621 // create the vector Val[idx64],Val[idx64+1],Val[idx64],Val[idx64+1],... 7622 SDValue TBL = DAG.getNode(AArch64ISD::TBL, DL, MVT::nxv2i64, V, ShuffleMask); 7623 return DAG.getNode(ISD::BITCAST, DL, VT, TBL); 7624 } 7625 7626 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits, 7627 APInt &UndefBits) { 7628 EVT VT = BVN->getValueType(0); 7629 APInt SplatBits, SplatUndef; 7630 unsigned SplatBitSize; 7631 bool HasAnyUndefs; 7632 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 7633 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize; 7634 7635 for (unsigned i = 0; i < NumSplats; ++i) { 7636 CnstBits <<= SplatBitSize; 7637 UndefBits <<= SplatBitSize; 7638 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits()); 7639 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits()); 7640 } 7641 7642 return true; 7643 } 7644 7645 return false; 7646 } 7647 7648 // Try 64-bit splatted SIMD immediate. 7649 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 7650 const APInt &Bits) { 7651 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 7652 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 7653 EVT VT = Op.getValueType(); 7654 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64; 7655 7656 if (AArch64_AM::isAdvSIMDModImmType10(Value)) { 7657 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value); 7658 7659 SDLoc dl(Op); 7660 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 7661 DAG.getConstant(Value, dl, MVT::i32)); 7662 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 7663 } 7664 } 7665 7666 return SDValue(); 7667 } 7668 7669 // Try 32-bit splatted SIMD immediate. 7670 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 7671 const APInt &Bits, 7672 const SDValue *LHS = nullptr) { 7673 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 7674 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 7675 EVT VT = Op.getValueType(); 7676 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 7677 bool isAdvSIMDModImm = false; 7678 uint64_t Shift; 7679 7680 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) { 7681 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value); 7682 Shift = 0; 7683 } 7684 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) { 7685 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value); 7686 Shift = 8; 7687 } 7688 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) { 7689 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value); 7690 Shift = 16; 7691 } 7692 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) { 7693 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value); 7694 Shift = 24; 7695 } 7696 7697 if (isAdvSIMDModImm) { 7698 SDLoc dl(Op); 7699 SDValue Mov; 7700 7701 if (LHS) 7702 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS, 7703 DAG.getConstant(Value, dl, MVT::i32), 7704 DAG.getConstant(Shift, dl, MVT::i32)); 7705 else 7706 Mov = DAG.getNode(NewOp, dl, MovTy, 7707 DAG.getConstant(Value, dl, MVT::i32), 7708 DAG.getConstant(Shift, dl, MVT::i32)); 7709 7710 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 7711 } 7712 } 7713 7714 return SDValue(); 7715 } 7716 7717 // Try 16-bit splatted SIMD immediate. 7718 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 7719 const APInt &Bits, 7720 const SDValue *LHS = nullptr) { 7721 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 7722 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 7723 EVT VT = Op.getValueType(); 7724 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 7725 bool isAdvSIMDModImm = false; 7726 uint64_t Shift; 7727 7728 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) { 7729 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value); 7730 Shift = 0; 7731 } 7732 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) { 7733 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value); 7734 Shift = 8; 7735 } 7736 7737 if (isAdvSIMDModImm) { 7738 SDLoc dl(Op); 7739 SDValue Mov; 7740 7741 if (LHS) 7742 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS, 7743 DAG.getConstant(Value, dl, MVT::i32), 7744 DAG.getConstant(Shift, dl, MVT::i32)); 7745 else 7746 Mov = DAG.getNode(NewOp, dl, MovTy, 7747 DAG.getConstant(Value, dl, MVT::i32), 7748 DAG.getConstant(Shift, dl, MVT::i32)); 7749 7750 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 7751 } 7752 } 7753 7754 return SDValue(); 7755 } 7756 7757 // Try 32-bit splatted SIMD immediate with shifted ones. 7758 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op, 7759 SelectionDAG &DAG, const APInt &Bits) { 7760 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 7761 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 7762 EVT VT = Op.getValueType(); 7763 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 7764 bool isAdvSIMDModImm = false; 7765 uint64_t Shift; 7766 7767 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) { 7768 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value); 7769 Shift = 264; 7770 } 7771 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) { 7772 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value); 7773 Shift = 272; 7774 } 7775 7776 if (isAdvSIMDModImm) { 7777 SDLoc dl(Op); 7778 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 7779 DAG.getConstant(Value, dl, MVT::i32), 7780 DAG.getConstant(Shift, dl, MVT::i32)); 7781 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 7782 } 7783 } 7784 7785 return SDValue(); 7786 } 7787 7788 // Try 8-bit splatted SIMD immediate. 7789 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 7790 const APInt &Bits) { 7791 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 7792 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 7793 EVT VT = Op.getValueType(); 7794 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8; 7795 7796 if (AArch64_AM::isAdvSIMDModImmType9(Value)) { 7797 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value); 7798 7799 SDLoc dl(Op); 7800 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 7801 DAG.getConstant(Value, dl, MVT::i32)); 7802 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 7803 } 7804 } 7805 7806 return SDValue(); 7807 } 7808 7809 // Try FP splatted SIMD immediate. 7810 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 7811 const APInt &Bits) { 7812 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 7813 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 7814 EVT VT = Op.getValueType(); 7815 bool isWide = (VT.getSizeInBits() == 128); 7816 MVT MovTy; 7817 bool isAdvSIMDModImm = false; 7818 7819 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) { 7820 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value); 7821 MovTy = isWide ? MVT::v4f32 : MVT::v2f32; 7822 } 7823 else if (isWide && 7824 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) { 7825 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value); 7826 MovTy = MVT::v2f64; 7827 } 7828 7829 if (isAdvSIMDModImm) { 7830 SDLoc dl(Op); 7831 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 7832 DAG.getConstant(Value, dl, MVT::i32)); 7833 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 7834 } 7835 } 7836 7837 return SDValue(); 7838 } 7839 7840 // Specialized code to quickly find if PotentialBVec is a BuildVector that 7841 // consists of only the same constant int value, returned in reference arg 7842 // ConstVal 7843 static bool isAllConstantBuildVector(const SDValue &PotentialBVec, 7844 uint64_t &ConstVal) { 7845 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec); 7846 if (!Bvec) 7847 return false; 7848 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0)); 7849 if (!FirstElt) 7850 return false; 7851 EVT VT = Bvec->getValueType(0); 7852 unsigned NumElts = VT.getVectorNumElements(); 7853 for (unsigned i = 1; i < NumElts; ++i) 7854 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt) 7855 return false; 7856 ConstVal = FirstElt->getZExtValue(); 7857 return true; 7858 } 7859 7860 static unsigned getIntrinsicID(const SDNode *N) { 7861 unsigned Opcode = N->getOpcode(); 7862 switch (Opcode) { 7863 default: 7864 return Intrinsic::not_intrinsic; 7865 case ISD::INTRINSIC_WO_CHAIN: { 7866 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7867 if (IID < Intrinsic::num_intrinsics) 7868 return IID; 7869 return Intrinsic::not_intrinsic; 7870 } 7871 } 7872 } 7873 7874 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)), 7875 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a 7876 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2. 7877 // Also, logical shift right -> sri, with the same structure. 7878 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) { 7879 EVT VT = N->getValueType(0); 7880 7881 if (!VT.isVector()) 7882 return SDValue(); 7883 7884 SDLoc DL(N); 7885 7886 // Is the first op an AND? 7887 const SDValue And = N->getOperand(0); 7888 if (And.getOpcode() != ISD::AND) 7889 return SDValue(); 7890 7891 // Is the second op an shl or lshr? 7892 SDValue Shift = N->getOperand(1); 7893 // This will have been turned into: AArch64ISD::VSHL vector, #shift 7894 // or AArch64ISD::VLSHR vector, #shift 7895 unsigned ShiftOpc = Shift.getOpcode(); 7896 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR)) 7897 return SDValue(); 7898 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR; 7899 7900 // Is the shift amount constant? 7901 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 7902 if (!C2node) 7903 return SDValue(); 7904 7905 // Is the and mask vector all constant? 7906 uint64_t C1; 7907 if (!isAllConstantBuildVector(And.getOperand(1), C1)) 7908 return SDValue(); 7909 7910 // Is C1 == ~C2, taking into account how much one can shift elements of a 7911 // particular size? 7912 uint64_t C2 = C2node->getZExtValue(); 7913 unsigned ElemSizeInBits = VT.getScalarSizeInBits(); 7914 if (C2 > ElemSizeInBits) 7915 return SDValue(); 7916 unsigned ElemMask = (1 << ElemSizeInBits) - 1; 7917 if ((C1 & ElemMask) != (~C2 & ElemMask)) 7918 return SDValue(); 7919 7920 SDValue X = And.getOperand(0); 7921 SDValue Y = Shift.getOperand(0); 7922 7923 unsigned Intrin = 7924 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli; 7925 SDValue ResultSLI = 7926 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 7927 DAG.getConstant(Intrin, DL, MVT::i32), X, Y, 7928 Shift.getOperand(1)); 7929 7930 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n"); 7931 LLVM_DEBUG(N->dump(&DAG)); 7932 LLVM_DEBUG(dbgs() << "into: \n"); 7933 LLVM_DEBUG(ResultSLI->dump(&DAG)); 7934 7935 ++NumShiftInserts; 7936 return ResultSLI; 7937 } 7938 7939 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op, 7940 SelectionDAG &DAG) const { 7941 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2)) 7942 if (EnableAArch64SlrGeneration) { 7943 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG)) 7944 return Res; 7945 } 7946 7947 EVT VT = Op.getValueType(); 7948 7949 SDValue LHS = Op.getOperand(0); 7950 BuildVectorSDNode *BVN = 7951 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode()); 7952 if (!BVN) { 7953 // OR commutes, so try swapping the operands. 7954 LHS = Op.getOperand(1); 7955 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode()); 7956 } 7957 if (!BVN) 7958 return Op; 7959 7960 APInt DefBits(VT.getSizeInBits(), 0); 7961 APInt UndefBits(VT.getSizeInBits(), 0); 7962 if (resolveBuildVector(BVN, DefBits, UndefBits)) { 7963 SDValue NewOp; 7964 7965 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG, 7966 DefBits, &LHS)) || 7967 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG, 7968 DefBits, &LHS))) 7969 return NewOp; 7970 7971 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG, 7972 UndefBits, &LHS)) || 7973 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG, 7974 UndefBits, &LHS))) 7975 return NewOp; 7976 } 7977 7978 // We can always fall back to a non-immediate OR. 7979 return Op; 7980 } 7981 7982 // Normalize the operands of BUILD_VECTOR. The value of constant operands will 7983 // be truncated to fit element width. 7984 static SDValue NormalizeBuildVector(SDValue Op, 7985 SelectionDAG &DAG) { 7986 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7987 SDLoc dl(Op); 7988 EVT VT = Op.getValueType(); 7989 EVT EltTy= VT.getVectorElementType(); 7990 7991 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16) 7992 return Op; 7993 7994 SmallVector<SDValue, 16> Ops; 7995 for (SDValue Lane : Op->ops()) { 7996 // For integer vectors, type legalization would have promoted the 7997 // operands already. Otherwise, if Op is a floating-point splat 7998 // (with operands cast to integers), then the only possibilities 7999 // are constants and UNDEFs. 8000 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) { 8001 APInt LowBits(EltTy.getSizeInBits(), 8002 CstLane->getZExtValue()); 8003 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32); 8004 } else if (Lane.getNode()->isUndef()) { 8005 Lane = DAG.getUNDEF(MVT::i32); 8006 } else { 8007 assert(Lane.getValueType() == MVT::i32 && 8008 "Unexpected BUILD_VECTOR operand type"); 8009 } 8010 Ops.push_back(Lane); 8011 } 8012 return DAG.getBuildVector(VT, dl, Ops); 8013 } 8014 8015 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) { 8016 EVT VT = Op.getValueType(); 8017 8018 APInt DefBits(VT.getSizeInBits(), 0); 8019 APInt UndefBits(VT.getSizeInBits(), 0); 8020 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 8021 if (resolveBuildVector(BVN, DefBits, UndefBits)) { 8022 SDValue NewOp; 8023 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) || 8024 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 8025 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) || 8026 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 8027 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) || 8028 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits))) 8029 return NewOp; 8030 8031 DefBits = ~DefBits; 8032 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) || 8033 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) || 8034 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits))) 8035 return NewOp; 8036 8037 DefBits = UndefBits; 8038 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) || 8039 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 8040 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) || 8041 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 8042 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) || 8043 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits))) 8044 return NewOp; 8045 8046 DefBits = ~UndefBits; 8047 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) || 8048 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) || 8049 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits))) 8050 return NewOp; 8051 } 8052 8053 return SDValue(); 8054 } 8055 8056 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op, 8057 SelectionDAG &DAG) const { 8058 EVT VT = Op.getValueType(); 8059 8060 // Try to build a simple constant vector. 8061 Op = NormalizeBuildVector(Op, DAG); 8062 if (VT.isInteger()) { 8063 // Certain vector constants, used to express things like logical NOT and 8064 // arithmetic NEG, are passed through unmodified. This allows special 8065 // patterns for these operations to match, which will lower these constants 8066 // to whatever is proven necessary. 8067 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 8068 if (BVN->isConstant()) 8069 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) { 8070 unsigned BitSize = VT.getVectorElementType().getSizeInBits(); 8071 APInt Val(BitSize, 8072 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue()); 8073 if (Val.isNullValue() || Val.isAllOnesValue()) 8074 return Op; 8075 } 8076 } 8077 8078 if (SDValue V = ConstantBuildVector(Op, DAG)) 8079 return V; 8080 8081 // Scan through the operands to find some interesting properties we can 8082 // exploit: 8083 // 1) If only one value is used, we can use a DUP, or 8084 // 2) if only the low element is not undef, we can just insert that, or 8085 // 3) if only one constant value is used (w/ some non-constant lanes), 8086 // we can splat the constant value into the whole vector then fill 8087 // in the non-constant lanes. 8088 // 4) FIXME: If different constant values are used, but we can intelligently 8089 // select the values we'll be overwriting for the non-constant 8090 // lanes such that we can directly materialize the vector 8091 // some other way (MOVI, e.g.), we can be sneaky. 8092 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP. 8093 SDLoc dl(Op); 8094 unsigned NumElts = VT.getVectorNumElements(); 8095 bool isOnlyLowElement = true; 8096 bool usesOnlyOneValue = true; 8097 bool usesOnlyOneConstantValue = true; 8098 bool isConstant = true; 8099 bool AllLanesExtractElt = true; 8100 unsigned NumConstantLanes = 0; 8101 SDValue Value; 8102 SDValue ConstantValue; 8103 for (unsigned i = 0; i < NumElts; ++i) { 8104 SDValue V = Op.getOperand(i); 8105 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 8106 AllLanesExtractElt = false; 8107 if (V.isUndef()) 8108 continue; 8109 if (i > 0) 8110 isOnlyLowElement = false; 8111 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 8112 isConstant = false; 8113 8114 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) { 8115 ++NumConstantLanes; 8116 if (!ConstantValue.getNode()) 8117 ConstantValue = V; 8118 else if (ConstantValue != V) 8119 usesOnlyOneConstantValue = false; 8120 } 8121 8122 if (!Value.getNode()) 8123 Value = V; 8124 else if (V != Value) 8125 usesOnlyOneValue = false; 8126 } 8127 8128 if (!Value.getNode()) { 8129 LLVM_DEBUG( 8130 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n"); 8131 return DAG.getUNDEF(VT); 8132 } 8133 8134 // Convert BUILD_VECTOR where all elements but the lowest are undef into 8135 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector 8136 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR. 8137 if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) { 8138 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 " 8139 "SCALAR_TO_VECTOR node\n"); 8140 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 8141 } 8142 8143 if (AllLanesExtractElt) { 8144 SDNode *Vector = nullptr; 8145 bool Even = false; 8146 bool Odd = false; 8147 // Check whether the extract elements match the Even pattern <0,2,4,...> or 8148 // the Odd pattern <1,3,5,...>. 8149 for (unsigned i = 0; i < NumElts; ++i) { 8150 SDValue V = Op.getOperand(i); 8151 const SDNode *N = V.getNode(); 8152 if (!isa<ConstantSDNode>(N->getOperand(1))) 8153 break; 8154 SDValue N0 = N->getOperand(0); 8155 8156 // All elements are extracted from the same vector. 8157 if (!Vector) { 8158 Vector = N0.getNode(); 8159 // Check that the type of EXTRACT_VECTOR_ELT matches the type of 8160 // BUILD_VECTOR. 8161 if (VT.getVectorElementType() != 8162 N0.getValueType().getVectorElementType()) 8163 break; 8164 } else if (Vector != N0.getNode()) { 8165 Odd = false; 8166 Even = false; 8167 break; 8168 } 8169 8170 // Extracted values are either at Even indices <0,2,4,...> or at Odd 8171 // indices <1,3,5,...>. 8172 uint64_t Val = N->getConstantOperandVal(1); 8173 if (Val == 2 * i) { 8174 Even = true; 8175 continue; 8176 } 8177 if (Val - 1 == 2 * i) { 8178 Odd = true; 8179 continue; 8180 } 8181 8182 // Something does not match: abort. 8183 Odd = false; 8184 Even = false; 8185 break; 8186 } 8187 if (Even || Odd) { 8188 SDValue LHS = 8189 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0), 8190 DAG.getConstant(0, dl, MVT::i64)); 8191 SDValue RHS = 8192 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0), 8193 DAG.getConstant(NumElts, dl, MVT::i64)); 8194 8195 if (Even && !Odd) 8196 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS, 8197 RHS); 8198 if (Odd && !Even) 8199 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS, 8200 RHS); 8201 } 8202 } 8203 8204 // Use DUP for non-constant splats. For f32 constant splats, reduce to 8205 // i32 and try again. 8206 if (usesOnlyOneValue) { 8207 if (!isConstant) { 8208 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 8209 Value.getValueType() != VT) { 8210 LLVM_DEBUG( 8211 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n"); 8212 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value); 8213 } 8214 8215 // This is actually a DUPLANExx operation, which keeps everything vectory. 8216 8217 SDValue Lane = Value.getOperand(1); 8218 Value = Value.getOperand(0); 8219 if (Value.getValueSizeInBits() == 64) { 8220 LLVM_DEBUG( 8221 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, " 8222 "widening it\n"); 8223 Value = WidenVector(Value, DAG); 8224 } 8225 8226 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType()); 8227 return DAG.getNode(Opcode, dl, VT, Value, Lane); 8228 } 8229 8230 if (VT.getVectorElementType().isFloatingPoint()) { 8231 SmallVector<SDValue, 8> Ops; 8232 EVT EltTy = VT.getVectorElementType(); 8233 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) && 8234 "Unsupported floating-point vector type"); 8235 LLVM_DEBUG( 8236 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int " 8237 "BITCASTS, and try again\n"); 8238 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits()); 8239 for (unsigned i = 0; i < NumElts; ++i) 8240 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i))); 8241 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts); 8242 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 8243 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: "; 8244 Val.dump();); 8245 Val = LowerBUILD_VECTOR(Val, DAG); 8246 if (Val.getNode()) 8247 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 8248 } 8249 } 8250 8251 // If there was only one constant value used and for more than one lane, 8252 // start by splatting that value, then replace the non-constant lanes. This 8253 // is better than the default, which will perform a separate initialization 8254 // for each lane. 8255 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) { 8256 // Firstly, try to materialize the splat constant. 8257 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue), 8258 Val = ConstantBuildVector(Vec, DAG); 8259 if (!Val) { 8260 // Otherwise, materialize the constant and splat it. 8261 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue); 8262 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val); 8263 } 8264 8265 // Now insert the non-constant lanes. 8266 for (unsigned i = 0; i < NumElts; ++i) { 8267 SDValue V = Op.getOperand(i); 8268 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 8269 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) 8270 // Note that type legalization likely mucked about with the VT of the 8271 // source operand, so we may have to convert it here before inserting. 8272 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx); 8273 } 8274 return Val; 8275 } 8276 8277 // This will generate a load from the constant pool. 8278 if (isConstant) { 8279 LLVM_DEBUG( 8280 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default " 8281 "expansion\n"); 8282 return SDValue(); 8283 } 8284 8285 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 8286 if (NumElts >= 4) { 8287 if (SDValue shuffle = ReconstructShuffle(Op, DAG)) 8288 return shuffle; 8289 } 8290 8291 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 8292 // know the default expansion would otherwise fall back on something even 8293 // worse. For a vector with one or two non-undef values, that's 8294 // scalar_to_vector for the elements followed by a shuffle (provided the 8295 // shuffle is valid for the target) and materialization element by element 8296 // on the stack followed by a load for everything else. 8297 if (!isConstant && !usesOnlyOneValue) { 8298 LLVM_DEBUG( 8299 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence " 8300 "of INSERT_VECTOR_ELT\n"); 8301 8302 SDValue Vec = DAG.getUNDEF(VT); 8303 SDValue Op0 = Op.getOperand(0); 8304 unsigned i = 0; 8305 8306 // Use SCALAR_TO_VECTOR for lane zero to 8307 // a) Avoid a RMW dependency on the full vector register, and 8308 // b) Allow the register coalescer to fold away the copy if the 8309 // value is already in an S or D register, and we're forced to emit an 8310 // INSERT_SUBREG that we can't fold anywhere. 8311 // 8312 // We also allow types like i8 and i16 which are illegal scalar but legal 8313 // vector element types. After type-legalization the inserted value is 8314 // extended (i32) and it is safe to cast them to the vector type by ignoring 8315 // the upper bits of the lowest lane (e.g. v8i8, v4i16). 8316 if (!Op0.isUndef()) { 8317 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n"); 8318 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0); 8319 ++i; 8320 } 8321 LLVM_DEBUG(if (i < NumElts) dbgs() 8322 << "Creating nodes for the other vector elements:\n";); 8323 for (; i < NumElts; ++i) { 8324 SDValue V = Op.getOperand(i); 8325 if (V.isUndef()) 8326 continue; 8327 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 8328 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 8329 } 8330 return Vec; 8331 } 8332 8333 LLVM_DEBUG( 8334 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find " 8335 "better alternative\n"); 8336 return SDValue(); 8337 } 8338 8339 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 8340 SelectionDAG &DAG) const { 8341 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!"); 8342 8343 // Check for non-constant or out of range lane. 8344 EVT VT = Op.getOperand(0).getValueType(); 8345 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 8346 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 8347 return SDValue(); 8348 8349 8350 // Insertion/extraction are legal for V128 types. 8351 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 8352 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 8353 VT == MVT::v8f16) 8354 return Op; 8355 8356 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 8357 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16) 8358 return SDValue(); 8359 8360 // For V64 types, we perform insertion by expanding the value 8361 // to a V128 type and perform the insertion on that. 8362 SDLoc DL(Op); 8363 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 8364 EVT WideTy = WideVec.getValueType(); 8365 8366 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec, 8367 Op.getOperand(1), Op.getOperand(2)); 8368 // Re-narrow the resultant vector. 8369 return NarrowVector(Node, DAG); 8370 } 8371 8372 SDValue 8373 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 8374 SelectionDAG &DAG) const { 8375 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!"); 8376 8377 // Check for non-constant or out of range lane. 8378 EVT VT = Op.getOperand(0).getValueType(); 8379 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8380 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 8381 return SDValue(); 8382 8383 8384 // Insertion/extraction are legal for V128 types. 8385 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 8386 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 8387 VT == MVT::v8f16) 8388 return Op; 8389 8390 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 8391 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16) 8392 return SDValue(); 8393 8394 // For V64 types, we perform extraction by expanding the value 8395 // to a V128 type and perform the extraction on that. 8396 SDLoc DL(Op); 8397 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 8398 EVT WideTy = WideVec.getValueType(); 8399 8400 EVT ExtrTy = WideTy.getVectorElementType(); 8401 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8) 8402 ExtrTy = MVT::i32; 8403 8404 // For extractions, we just return the result directly. 8405 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec, 8406 Op.getOperand(1)); 8407 } 8408 8409 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, 8410 SelectionDAG &DAG) const { 8411 EVT VT = Op.getOperand(0).getValueType(); 8412 SDLoc dl(Op); 8413 // Just in case... 8414 if (!VT.isVector()) 8415 return SDValue(); 8416 8417 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8418 if (!Cst) 8419 return SDValue(); 8420 unsigned Val = Cst->getZExtValue(); 8421 8422 unsigned Size = Op.getValueSizeInBits(); 8423 8424 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel. 8425 if (Val == 0) 8426 return Op; 8427 8428 // If this is extracting the upper 64-bits of a 128-bit vector, we match 8429 // that directly. 8430 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64) 8431 return Op; 8432 8433 return SDValue(); 8434 } 8435 8436 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 8437 if (VT.getVectorNumElements() == 4 && 8438 (VT.is128BitVector() || VT.is64BitVector())) { 8439 unsigned PFIndexes[4]; 8440 for (unsigned i = 0; i != 4; ++i) { 8441 if (M[i] < 0) 8442 PFIndexes[i] = 8; 8443 else 8444 PFIndexes[i] = M[i]; 8445 } 8446 8447 // Compute the index in the perfect shuffle table. 8448 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 8449 PFIndexes[2] * 9 + PFIndexes[3]; 8450 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 8451 unsigned Cost = (PFEntry >> 30); 8452 8453 if (Cost <= 4) 8454 return true; 8455 } 8456 8457 bool DummyBool; 8458 int DummyInt; 8459 unsigned DummyUnsigned; 8460 8461 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) || 8462 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) || 8463 isEXTMask(M, VT, DummyBool, DummyUnsigned) || 8464 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM. 8465 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) || 8466 isZIPMask(M, VT, DummyUnsigned) || 8467 isTRN_v_undef_Mask(M, VT, DummyUnsigned) || 8468 isUZP_v_undef_Mask(M, VT, DummyUnsigned) || 8469 isZIP_v_undef_Mask(M, VT, DummyUnsigned) || 8470 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) || 8471 isConcatMask(M, VT, VT.getSizeInBits() == 128)); 8472 } 8473 8474 /// getVShiftImm - Check if this is a valid build_vector for the immediate 8475 /// operand of a vector shift operation, where all the elements of the 8476 /// build_vector must have the same constant integer value. 8477 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 8478 // Ignore bit_converts. 8479 while (Op.getOpcode() == ISD::BITCAST) 8480 Op = Op.getOperand(0); 8481 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 8482 APInt SplatBits, SplatUndef; 8483 unsigned SplatBitSize; 8484 bool HasAnyUndefs; 8485 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 8486 HasAnyUndefs, ElementBits) || 8487 SplatBitSize > ElementBits) 8488 return false; 8489 Cnt = SplatBits.getSExtValue(); 8490 return true; 8491 } 8492 8493 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 8494 /// operand of a vector shift left operation. That value must be in the range: 8495 /// 0 <= Value < ElementBits for a left shift; or 8496 /// 0 <= Value <= ElementBits for a long left shift. 8497 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 8498 assert(VT.isVector() && "vector shift count is not a vector type"); 8499 int64_t ElementBits = VT.getScalarSizeInBits(); 8500 if (!getVShiftImm(Op, ElementBits, Cnt)) 8501 return false; 8502 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 8503 } 8504 8505 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 8506 /// operand of a vector shift right operation. The value must be in the range: 8507 /// 1 <= Value <= ElementBits for a right shift; or 8508 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) { 8509 assert(VT.isVector() && "vector shift count is not a vector type"); 8510 int64_t ElementBits = VT.getScalarSizeInBits(); 8511 if (!getVShiftImm(Op, ElementBits, Cnt)) 8512 return false; 8513 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 8514 } 8515 8516 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op, 8517 SelectionDAG &DAG) const { 8518 EVT VT = Op.getValueType(); 8519 SDLoc DL(Op); 8520 int64_t Cnt; 8521 8522 if (!Op.getOperand(1).getValueType().isVector()) 8523 return Op; 8524 unsigned EltSize = VT.getScalarSizeInBits(); 8525 8526 switch (Op.getOpcode()) { 8527 default: 8528 llvm_unreachable("unexpected shift opcode"); 8529 8530 case ISD::SHL: 8531 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) 8532 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0), 8533 DAG.getConstant(Cnt, DL, MVT::i32)); 8534 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 8535 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL, 8536 MVT::i32), 8537 Op.getOperand(0), Op.getOperand(1)); 8538 case ISD::SRA: 8539 case ISD::SRL: 8540 // Right shift immediate 8541 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) { 8542 unsigned Opc = 8543 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR; 8544 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), 8545 DAG.getConstant(Cnt, DL, MVT::i32)); 8546 } 8547 8548 // Right shift register. Note, there is not a shift right register 8549 // instruction, but the shift left register instruction takes a signed 8550 // value, where negative numbers specify a right shift. 8551 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl 8552 : Intrinsic::aarch64_neon_ushl; 8553 // negate the shift amount 8554 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1)); 8555 SDValue NegShiftLeft = 8556 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 8557 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0), 8558 NegShift); 8559 return NegShiftLeft; 8560 } 8561 8562 return SDValue(); 8563 } 8564 8565 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS, 8566 AArch64CC::CondCode CC, bool NoNans, EVT VT, 8567 const SDLoc &dl, SelectionDAG &DAG) { 8568 EVT SrcVT = LHS.getValueType(); 8569 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() && 8570 "function only supposed to emit natural comparisons"); 8571 8572 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 8573 APInt CnstBits(VT.getSizeInBits(), 0); 8574 APInt UndefBits(VT.getSizeInBits(), 0); 8575 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits); 8576 bool IsZero = IsCnst && (CnstBits == 0); 8577 8578 if (SrcVT.getVectorElementType().isFloatingPoint()) { 8579 switch (CC) { 8580 default: 8581 return SDValue(); 8582 case AArch64CC::NE: { 8583 SDValue Fcmeq; 8584 if (IsZero) 8585 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 8586 else 8587 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 8588 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq); 8589 } 8590 case AArch64CC::EQ: 8591 if (IsZero) 8592 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 8593 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 8594 case AArch64CC::GE: 8595 if (IsZero) 8596 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS); 8597 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS); 8598 case AArch64CC::GT: 8599 if (IsZero) 8600 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS); 8601 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS); 8602 case AArch64CC::LS: 8603 if (IsZero) 8604 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS); 8605 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS); 8606 case AArch64CC::LT: 8607 if (!NoNans) 8608 return SDValue(); 8609 // If we ignore NaNs then we can use to the MI implementation. 8610 LLVM_FALLTHROUGH; 8611 case AArch64CC::MI: 8612 if (IsZero) 8613 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS); 8614 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS); 8615 } 8616 } 8617 8618 switch (CC) { 8619 default: 8620 return SDValue(); 8621 case AArch64CC::NE: { 8622 SDValue Cmeq; 8623 if (IsZero) 8624 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 8625 else 8626 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 8627 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq); 8628 } 8629 case AArch64CC::EQ: 8630 if (IsZero) 8631 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 8632 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 8633 case AArch64CC::GE: 8634 if (IsZero) 8635 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS); 8636 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS); 8637 case AArch64CC::GT: 8638 if (IsZero) 8639 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS); 8640 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS); 8641 case AArch64CC::LE: 8642 if (IsZero) 8643 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS); 8644 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS); 8645 case AArch64CC::LS: 8646 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS); 8647 case AArch64CC::LO: 8648 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS); 8649 case AArch64CC::LT: 8650 if (IsZero) 8651 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS); 8652 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS); 8653 case AArch64CC::HI: 8654 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS); 8655 case AArch64CC::HS: 8656 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS); 8657 } 8658 } 8659 8660 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op, 8661 SelectionDAG &DAG) const { 8662 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 8663 SDValue LHS = Op.getOperand(0); 8664 SDValue RHS = Op.getOperand(1); 8665 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger(); 8666 SDLoc dl(Op); 8667 8668 if (LHS.getValueType().getVectorElementType().isInteger()) { 8669 assert(LHS.getValueType() == RHS.getValueType()); 8670 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 8671 SDValue Cmp = 8672 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG); 8673 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 8674 } 8675 8676 const bool FullFP16 = 8677 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 8678 8679 // Make v4f16 (only) fcmp operations utilise vector instructions 8680 // v8f16 support will be a litle more complicated 8681 if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) { 8682 if (LHS.getValueType().getVectorNumElements() == 4) { 8683 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS); 8684 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS); 8685 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC); 8686 DAG.ReplaceAllUsesWith(Op, NewSetcc); 8687 CmpVT = MVT::v4i32; 8688 } else 8689 return SDValue(); 8690 } 8691 8692 assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) || 8693 LHS.getValueType().getVectorElementType() != MVT::f128); 8694 8695 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 8696 // clean. Some of them require two branches to implement. 8697 AArch64CC::CondCode CC1, CC2; 8698 bool ShouldInvert; 8699 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert); 8700 8701 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath; 8702 SDValue Cmp = 8703 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG); 8704 if (!Cmp.getNode()) 8705 return SDValue(); 8706 8707 if (CC2 != AArch64CC::AL) { 8708 SDValue Cmp2 = 8709 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG); 8710 if (!Cmp2.getNode()) 8711 return SDValue(); 8712 8713 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2); 8714 } 8715 8716 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 8717 8718 if (ShouldInvert) 8719 Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType()); 8720 8721 return Cmp; 8722 } 8723 8724 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp, 8725 SelectionDAG &DAG) { 8726 SDValue VecOp = ScalarOp.getOperand(0); 8727 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp); 8728 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx, 8729 DAG.getConstant(0, DL, MVT::i64)); 8730 } 8731 8732 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op, 8733 SelectionDAG &DAG) const { 8734 SDLoc dl(Op); 8735 switch (Op.getOpcode()) { 8736 case ISD::VECREDUCE_ADD: 8737 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG); 8738 case ISD::VECREDUCE_SMAX: 8739 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG); 8740 case ISD::VECREDUCE_SMIN: 8741 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG); 8742 case ISD::VECREDUCE_UMAX: 8743 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG); 8744 case ISD::VECREDUCE_UMIN: 8745 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG); 8746 case ISD::VECREDUCE_FMAX: { 8747 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag"); 8748 return DAG.getNode( 8749 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), 8750 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32), 8751 Op.getOperand(0)); 8752 } 8753 case ISD::VECREDUCE_FMIN: { 8754 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag"); 8755 return DAG.getNode( 8756 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), 8757 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32), 8758 Op.getOperand(0)); 8759 } 8760 default: 8761 llvm_unreachable("Unhandled reduction"); 8762 } 8763 } 8764 8765 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op, 8766 SelectionDAG &DAG) const { 8767 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget()); 8768 if (!Subtarget.hasLSE()) 8769 return SDValue(); 8770 8771 // LSE has an atomic load-add instruction, but not a load-sub. 8772 SDLoc dl(Op); 8773 MVT VT = Op.getSimpleValueType(); 8774 SDValue RHS = Op.getOperand(2); 8775 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode()); 8776 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS); 8777 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(), 8778 Op.getOperand(0), Op.getOperand(1), RHS, 8779 AN->getMemOperand()); 8780 } 8781 8782 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op, 8783 SelectionDAG &DAG) const { 8784 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget()); 8785 if (!Subtarget.hasLSE()) 8786 return SDValue(); 8787 8788 // LSE has an atomic load-clear instruction, but not a load-and. 8789 SDLoc dl(Op); 8790 MVT VT = Op.getSimpleValueType(); 8791 SDValue RHS = Op.getOperand(2); 8792 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode()); 8793 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS); 8794 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(), 8795 Op.getOperand(0), Op.getOperand(1), RHS, 8796 AN->getMemOperand()); 8797 } 8798 8799 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC( 8800 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const { 8801 SDLoc dl(Op); 8802 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 8803 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0); 8804 8805 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 8806 const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask(); 8807 if (Subtarget->hasCustomCallingConv()) 8808 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask); 8809 8810 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size, 8811 DAG.getConstant(4, dl, MVT::i64)); 8812 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue()); 8813 Chain = 8814 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue), 8815 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64), 8816 DAG.getRegisterMask(Mask), Chain.getValue(1)); 8817 // To match the actual intent better, we should read the output from X15 here 8818 // again (instead of potentially spilling it to the stack), but rereading Size 8819 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined 8820 // here. 8821 8822 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size, 8823 DAG.getConstant(4, dl, MVT::i64)); 8824 return Chain; 8825 } 8826 8827 SDValue 8828 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 8829 SelectionDAG &DAG) const { 8830 assert(Subtarget->isTargetWindows() && 8831 "Only Windows alloca probing supported"); 8832 SDLoc dl(Op); 8833 // Get the inputs. 8834 SDNode *Node = Op.getNode(); 8835 SDValue Chain = Op.getOperand(0); 8836 SDValue Size = Op.getOperand(1); 8837 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 8838 EVT VT = Node->getValueType(0); 8839 8840 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 8841 "no-stack-arg-probe")) { 8842 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64); 8843 Chain = SP.getValue(1); 8844 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size); 8845 if (Align) 8846 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0), 8847 DAG.getConstant(-(uint64_t)Align, dl, VT)); 8848 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP); 8849 SDValue Ops[2] = {SP, Chain}; 8850 return DAG.getMergeValues(Ops, dl); 8851 } 8852 8853 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 8854 8855 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG); 8856 8857 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64); 8858 Chain = SP.getValue(1); 8859 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size); 8860 if (Align) 8861 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0), 8862 DAG.getConstant(-(uint64_t)Align, dl, VT)); 8863 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP); 8864 8865 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true), 8866 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 8867 8868 SDValue Ops[2] = {SP, Chain}; 8869 return DAG.getMergeValues(Ops, dl); 8870 } 8871 8872 SDValue AArch64TargetLowering::LowerVSCALE(SDValue Op, 8873 SelectionDAG &DAG) const { 8874 EVT VT = Op.getValueType(); 8875 assert(VT != MVT::i64 && "Expected illegal VSCALE node"); 8876 8877 SDLoc DL(Op); 8878 APInt MulImm = cast<ConstantSDNode>(Op.getOperand(0))->getAPIntValue(); 8879 return DAG.getZExtOrTrunc(DAG.getVScale(DL, MVT::i64, MulImm.sextOrSelf(64)), 8880 DL, VT); 8881 } 8882 8883 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 8884 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 8885 /// specified in the intrinsic calls. 8886 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 8887 const CallInst &I, 8888 MachineFunction &MF, 8889 unsigned Intrinsic) const { 8890 auto &DL = I.getModule()->getDataLayout(); 8891 switch (Intrinsic) { 8892 case Intrinsic::aarch64_neon_ld2: 8893 case Intrinsic::aarch64_neon_ld3: 8894 case Intrinsic::aarch64_neon_ld4: 8895 case Intrinsic::aarch64_neon_ld1x2: 8896 case Intrinsic::aarch64_neon_ld1x3: 8897 case Intrinsic::aarch64_neon_ld1x4: 8898 case Intrinsic::aarch64_neon_ld2lane: 8899 case Intrinsic::aarch64_neon_ld3lane: 8900 case Intrinsic::aarch64_neon_ld4lane: 8901 case Intrinsic::aarch64_neon_ld2r: 8902 case Intrinsic::aarch64_neon_ld3r: 8903 case Intrinsic::aarch64_neon_ld4r: { 8904 Info.opc = ISD::INTRINSIC_W_CHAIN; 8905 // Conservatively set memVT to the entire set of vectors loaded. 8906 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 8907 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 8908 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 8909 Info.offset = 0; 8910 Info.align.reset(); 8911 // volatile loads with NEON intrinsics not supported 8912 Info.flags = MachineMemOperand::MOLoad; 8913 return true; 8914 } 8915 case Intrinsic::aarch64_neon_st2: 8916 case Intrinsic::aarch64_neon_st3: 8917 case Intrinsic::aarch64_neon_st4: 8918 case Intrinsic::aarch64_neon_st1x2: 8919 case Intrinsic::aarch64_neon_st1x3: 8920 case Intrinsic::aarch64_neon_st1x4: 8921 case Intrinsic::aarch64_neon_st2lane: 8922 case Intrinsic::aarch64_neon_st3lane: 8923 case Intrinsic::aarch64_neon_st4lane: { 8924 Info.opc = ISD::INTRINSIC_VOID; 8925 // Conservatively set memVT to the entire set of vectors stored. 8926 unsigned NumElts = 0; 8927 for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 8928 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 8929 if (!ArgTy->isVectorTy()) 8930 break; 8931 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 8932 } 8933 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 8934 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 8935 Info.offset = 0; 8936 Info.align.reset(); 8937 // volatile stores with NEON intrinsics not supported 8938 Info.flags = MachineMemOperand::MOStore; 8939 return true; 8940 } 8941 case Intrinsic::aarch64_ldaxr: 8942 case Intrinsic::aarch64_ldxr: { 8943 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 8944 Info.opc = ISD::INTRINSIC_W_CHAIN; 8945 Info.memVT = MVT::getVT(PtrTy->getElementType()); 8946 Info.ptrVal = I.getArgOperand(0); 8947 Info.offset = 0; 8948 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType())); 8949 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 8950 return true; 8951 } 8952 case Intrinsic::aarch64_stlxr: 8953 case Intrinsic::aarch64_stxr: { 8954 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 8955 Info.opc = ISD::INTRINSIC_W_CHAIN; 8956 Info.memVT = MVT::getVT(PtrTy->getElementType()); 8957 Info.ptrVal = I.getArgOperand(1); 8958 Info.offset = 0; 8959 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType())); 8960 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 8961 return true; 8962 } 8963 case Intrinsic::aarch64_ldaxp: 8964 case Intrinsic::aarch64_ldxp: 8965 Info.opc = ISD::INTRINSIC_W_CHAIN; 8966 Info.memVT = MVT::i128; 8967 Info.ptrVal = I.getArgOperand(0); 8968 Info.offset = 0; 8969 Info.align = Align(16); 8970 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 8971 return true; 8972 case Intrinsic::aarch64_stlxp: 8973 case Intrinsic::aarch64_stxp: 8974 Info.opc = ISD::INTRINSIC_W_CHAIN; 8975 Info.memVT = MVT::i128; 8976 Info.ptrVal = I.getArgOperand(2); 8977 Info.offset = 0; 8978 Info.align = Align(16); 8979 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 8980 return true; 8981 case Intrinsic::aarch64_sve_ld1: 8982 case Intrinsic::aarch64_sve_ldnt1: { 8983 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 8984 Info.opc = ISD::INTRINSIC_W_CHAIN; 8985 Info.memVT = MVT::getVT(I.getType()); 8986 Info.ptrVal = I.getArgOperand(1); 8987 Info.offset = 0; 8988 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType())); 8989 Info.flags = MachineMemOperand::MOLoad; 8990 if (Intrinsic == Intrinsic::aarch64_sve_ldnt1) 8991 Info.flags |= MachineMemOperand::MONonTemporal; 8992 return true; 8993 } 8994 case Intrinsic::aarch64_sve_st1: 8995 case Intrinsic::aarch64_sve_stnt1: { 8996 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(2)->getType()); 8997 Info.opc = ISD::INTRINSIC_W_CHAIN; 8998 Info.memVT = MVT::getVT(I.getOperand(0)->getType()); 8999 Info.ptrVal = I.getArgOperand(2); 9000 Info.offset = 0; 9001 Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType())); 9002 Info.flags = MachineMemOperand::MOStore; 9003 if (Intrinsic == Intrinsic::aarch64_sve_stnt1) 9004 Info.flags |= MachineMemOperand::MONonTemporal; 9005 return true; 9006 } 9007 default: 9008 break; 9009 } 9010 9011 return false; 9012 } 9013 9014 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load, 9015 ISD::LoadExtType ExtTy, 9016 EVT NewVT) const { 9017 // TODO: This may be worth removing. Check regression tests for diffs. 9018 if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT)) 9019 return false; 9020 9021 // If we're reducing the load width in order to avoid having to use an extra 9022 // instruction to do extension then it's probably a good idea. 9023 if (ExtTy != ISD::NON_EXTLOAD) 9024 return true; 9025 // Don't reduce load width if it would prevent us from combining a shift into 9026 // the offset. 9027 MemSDNode *Mem = dyn_cast<MemSDNode>(Load); 9028 assert(Mem); 9029 const SDValue &Base = Mem->getBasePtr(); 9030 if (Base.getOpcode() == ISD::ADD && 9031 Base.getOperand(1).getOpcode() == ISD::SHL && 9032 Base.getOperand(1).hasOneUse() && 9033 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) { 9034 // The shift can be combined if it matches the size of the value being 9035 // loaded (and so reducing the width would make it not match). 9036 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1); 9037 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8; 9038 if (ShiftAmount == Log2_32(LoadBytes)) 9039 return false; 9040 } 9041 // We have no reason to disallow reducing the load width, so allow it. 9042 return true; 9043 } 9044 9045 // Truncations from 64-bit GPR to 32-bit GPR is free. 9046 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 9047 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 9048 return false; 9049 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 9050 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 9051 return NumBits1 > NumBits2; 9052 } 9053 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 9054 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 9055 return false; 9056 unsigned NumBits1 = VT1.getSizeInBits(); 9057 unsigned NumBits2 = VT2.getSizeInBits(); 9058 return NumBits1 > NumBits2; 9059 } 9060 9061 /// Check if it is profitable to hoist instruction in then/else to if. 9062 /// Not profitable if I and it's user can form a FMA instruction 9063 /// because we prefer FMSUB/FMADD. 9064 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const { 9065 if (I->getOpcode() != Instruction::FMul) 9066 return true; 9067 9068 if (!I->hasOneUse()) 9069 return true; 9070 9071 Instruction *User = I->user_back(); 9072 9073 if (User && 9074 !(User->getOpcode() == Instruction::FSub || 9075 User->getOpcode() == Instruction::FAdd)) 9076 return true; 9077 9078 const TargetOptions &Options = getTargetMachine().Options; 9079 const Function *F = I->getFunction(); 9080 const DataLayout &DL = F->getParent()->getDataLayout(); 9081 Type *Ty = User->getOperand(0)->getType(); 9082 9083 return !(isFMAFasterThanFMulAndFAdd(*F, Ty) && 9084 isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) && 9085 (Options.AllowFPOpFusion == FPOpFusion::Fast || 9086 Options.UnsafeFPMath)); 9087 } 9088 9089 // All 32-bit GPR operations implicitly zero the high-half of the corresponding 9090 // 64-bit GPR. 9091 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const { 9092 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 9093 return false; 9094 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 9095 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 9096 return NumBits1 == 32 && NumBits2 == 64; 9097 } 9098 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 9099 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 9100 return false; 9101 unsigned NumBits1 = VT1.getSizeInBits(); 9102 unsigned NumBits2 = VT2.getSizeInBits(); 9103 return NumBits1 == 32 && NumBits2 == 64; 9104 } 9105 9106 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 9107 EVT VT1 = Val.getValueType(); 9108 if (isZExtFree(VT1, VT2)) { 9109 return true; 9110 } 9111 9112 if (Val.getOpcode() != ISD::LOAD) 9113 return false; 9114 9115 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend. 9116 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() && 9117 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() && 9118 VT1.getSizeInBits() <= 32); 9119 } 9120 9121 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const { 9122 if (isa<FPExtInst>(Ext)) 9123 return false; 9124 9125 // Vector types are not free. 9126 if (Ext->getType()->isVectorTy()) 9127 return false; 9128 9129 for (const Use &U : Ext->uses()) { 9130 // The extension is free if we can fold it with a left shift in an 9131 // addressing mode or an arithmetic operation: add, sub, and cmp. 9132 9133 // Is there a shift? 9134 const Instruction *Instr = cast<Instruction>(U.getUser()); 9135 9136 // Is this a constant shift? 9137 switch (Instr->getOpcode()) { 9138 case Instruction::Shl: 9139 if (!isa<ConstantInt>(Instr->getOperand(1))) 9140 return false; 9141 break; 9142 case Instruction::GetElementPtr: { 9143 gep_type_iterator GTI = gep_type_begin(Instr); 9144 auto &DL = Ext->getModule()->getDataLayout(); 9145 std::advance(GTI, U.getOperandNo()-1); 9146 Type *IdxTy = GTI.getIndexedType(); 9147 // This extension will end up with a shift because of the scaling factor. 9148 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0. 9149 // Get the shift amount based on the scaling factor: 9150 // log2(sizeof(IdxTy)) - log2(8). 9151 uint64_t ShiftAmt = 9152 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3; 9153 // Is the constant foldable in the shift of the addressing mode? 9154 // I.e., shift amount is between 1 and 4 inclusive. 9155 if (ShiftAmt == 0 || ShiftAmt > 4) 9156 return false; 9157 break; 9158 } 9159 case Instruction::Trunc: 9160 // Check if this is a noop. 9161 // trunc(sext ty1 to ty2) to ty1. 9162 if (Instr->getType() == Ext->getOperand(0)->getType()) 9163 continue; 9164 LLVM_FALLTHROUGH; 9165 default: 9166 return false; 9167 } 9168 9169 // At this point we can use the bfm family, so this extension is free 9170 // for that use. 9171 } 9172 return true; 9173 } 9174 9175 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower 9176 /// or upper half of the vector elements. 9177 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) { 9178 auto areTypesHalfed = [](Value *FullV, Value *HalfV) { 9179 auto *FullVT = cast<VectorType>(FullV->getType()); 9180 auto *HalfVT = cast<VectorType>(HalfV->getType()); 9181 return FullVT->getBitWidth() == 2 * HalfVT->getBitWidth(); 9182 }; 9183 9184 auto extractHalf = [](Value *FullV, Value *HalfV) { 9185 auto *FullVT = cast<VectorType>(FullV->getType()); 9186 auto *HalfVT = cast<VectorType>(HalfV->getType()); 9187 return FullVT->getNumElements() == 2 * HalfVT->getNumElements(); 9188 }; 9189 9190 Constant *M1, *M2; 9191 Value *S1Op1, *S2Op1; 9192 if (!match(Op1, m_ShuffleVector(m_Value(S1Op1), m_Undef(), m_Constant(M1))) || 9193 !match(Op2, m_ShuffleVector(m_Value(S2Op1), m_Undef(), m_Constant(M2)))) 9194 return false; 9195 9196 // Check that the operands are half as wide as the result and we extract 9197 // half of the elements of the input vectors. 9198 if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) || 9199 !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2)) 9200 return false; 9201 9202 // Check the mask extracts either the lower or upper half of vector 9203 // elements. 9204 int M1Start = -1; 9205 int M2Start = -1; 9206 int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2; 9207 if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) || 9208 !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) || 9209 M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2))) 9210 return false; 9211 9212 return true; 9213 } 9214 9215 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth 9216 /// of the vector elements. 9217 static bool areExtractExts(Value *Ext1, Value *Ext2) { 9218 auto areExtDoubled = [](Instruction *Ext) { 9219 return Ext->getType()->getScalarSizeInBits() == 9220 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits(); 9221 }; 9222 9223 if (!match(Ext1, m_ZExtOrSExt(m_Value())) || 9224 !match(Ext2, m_ZExtOrSExt(m_Value())) || 9225 !areExtDoubled(cast<Instruction>(Ext1)) || 9226 !areExtDoubled(cast<Instruction>(Ext2))) 9227 return false; 9228 9229 return true; 9230 } 9231 9232 /// Check if sinking \p I's operands to I's basic block is profitable, because 9233 /// the operands can be folded into a target instruction, e.g. 9234 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2). 9235 bool AArch64TargetLowering::shouldSinkOperands( 9236 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 9237 if (!I->getType()->isVectorTy()) 9238 return false; 9239 9240 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 9241 switch (II->getIntrinsicID()) { 9242 case Intrinsic::aarch64_neon_umull: 9243 if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1))) 9244 return false; 9245 Ops.push_back(&II->getOperandUse(0)); 9246 Ops.push_back(&II->getOperandUse(1)); 9247 return true; 9248 default: 9249 return false; 9250 } 9251 } 9252 9253 switch (I->getOpcode()) { 9254 case Instruction::Sub: 9255 case Instruction::Add: { 9256 if (!areExtractExts(I->getOperand(0), I->getOperand(1))) 9257 return false; 9258 9259 // If the exts' operands extract either the lower or upper elements, we 9260 // can sink them too. 9261 auto Ext1 = cast<Instruction>(I->getOperand(0)); 9262 auto Ext2 = cast<Instruction>(I->getOperand(1)); 9263 if (areExtractShuffleVectors(Ext1, Ext2)) { 9264 Ops.push_back(&Ext1->getOperandUse(0)); 9265 Ops.push_back(&Ext2->getOperandUse(0)); 9266 } 9267 9268 Ops.push_back(&I->getOperandUse(0)); 9269 Ops.push_back(&I->getOperandUse(1)); 9270 9271 return true; 9272 } 9273 default: 9274 return false; 9275 } 9276 return false; 9277 } 9278 9279 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType, 9280 unsigned &RequiredAligment) const { 9281 if (!LoadedType.isSimple() || 9282 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint())) 9283 return false; 9284 // Cyclone supports unaligned accesses. 9285 RequiredAligment = 0; 9286 unsigned NumBits = LoadedType.getSizeInBits(); 9287 return NumBits == 32 || NumBits == 64; 9288 } 9289 9290 /// A helper function for determining the number of interleaved accesses we 9291 /// will generate when lowering accesses of the given type. 9292 unsigned 9293 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 9294 const DataLayout &DL) const { 9295 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 9296 } 9297 9298 MachineMemOperand::Flags 9299 AArch64TargetLowering::getTargetMMOFlags(const Instruction &I) const { 9300 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor && 9301 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr) 9302 return MOStridedAccess; 9303 return MachineMemOperand::MONone; 9304 } 9305 9306 bool AArch64TargetLowering::isLegalInterleavedAccessType( 9307 VectorType *VecTy, const DataLayout &DL) const { 9308 9309 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 9310 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 9311 9312 // Ensure the number of vector elements is greater than 1. 9313 if (VecTy->getNumElements() < 2) 9314 return false; 9315 9316 // Ensure the element type is legal. 9317 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64) 9318 return false; 9319 9320 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 9321 // 128 will be split into multiple interleaved accesses. 9322 return VecSize == 64 || VecSize % 128 == 0; 9323 } 9324 9325 /// Lower an interleaved load into a ldN intrinsic. 9326 /// 9327 /// E.g. Lower an interleaved load (Factor = 2): 9328 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr 9329 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 9330 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 9331 /// 9332 /// Into: 9333 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr) 9334 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0 9335 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1 9336 bool AArch64TargetLowering::lowerInterleavedLoad( 9337 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 9338 ArrayRef<unsigned> Indices, unsigned Factor) const { 9339 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 9340 "Invalid interleave factor"); 9341 assert(!Shuffles.empty() && "Empty shufflevector input"); 9342 assert(Shuffles.size() == Indices.size() && 9343 "Unmatched number of shufflevectors and indices"); 9344 9345 const DataLayout &DL = LI->getModule()->getDataLayout(); 9346 9347 VectorType *VecTy = Shuffles[0]->getType(); 9348 9349 // Skip if we do not have NEON and skip illegal vector types. We can 9350 // "legalize" wide vector types into multiple interleaved accesses as long as 9351 // the vector types are divisible by 128. 9352 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 9353 return false; 9354 9355 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 9356 9357 // A pointer vector can not be the return type of the ldN intrinsics. Need to 9358 // load integer vectors first and then convert to pointer vectors. 9359 Type *EltTy = VecTy->getVectorElementType(); 9360 if (EltTy->isPointerTy()) 9361 VecTy = 9362 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 9363 9364 IRBuilder<> Builder(LI); 9365 9366 // The base address of the load. 9367 Value *BaseAddr = LI->getPointerOperand(); 9368 9369 if (NumLoads > 1) { 9370 // If we're going to generate more than one load, reset the sub-vector type 9371 // to something legal. 9372 VecTy = VectorType::get(VecTy->getVectorElementType(), 9373 VecTy->getVectorNumElements() / NumLoads); 9374 9375 // We will compute the pointer operand of each load from the original base 9376 // address using GEPs. Cast the base address to a pointer to the scalar 9377 // element type. 9378 BaseAddr = Builder.CreateBitCast( 9379 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 9380 LI->getPointerAddressSpace())); 9381 } 9382 9383 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace()); 9384 Type *Tys[2] = {VecTy, PtrTy}; 9385 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2, 9386 Intrinsic::aarch64_neon_ld3, 9387 Intrinsic::aarch64_neon_ld4}; 9388 Function *LdNFunc = 9389 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 9390 9391 // Holds sub-vectors extracted from the load intrinsic return values. The 9392 // sub-vectors are associated with the shufflevector instructions they will 9393 // replace. 9394 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 9395 9396 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 9397 9398 // If we're generating more than one load, compute the base address of 9399 // subsequent loads as an offset from the previous. 9400 if (LoadCount > 0) 9401 BaseAddr = 9402 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr, 9403 VecTy->getVectorNumElements() * Factor); 9404 9405 CallInst *LdN = Builder.CreateCall( 9406 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN"); 9407 9408 // Extract and store the sub-vectors returned by the load intrinsic. 9409 for (unsigned i = 0; i < Shuffles.size(); i++) { 9410 ShuffleVectorInst *SVI = Shuffles[i]; 9411 unsigned Index = Indices[i]; 9412 9413 Value *SubVec = Builder.CreateExtractValue(LdN, Index); 9414 9415 // Convert the integer vector to pointer vector if the element is pointer. 9416 if (EltTy->isPointerTy()) 9417 SubVec = Builder.CreateIntToPtr( 9418 SubVec, VectorType::get(SVI->getType()->getVectorElementType(), 9419 VecTy->getVectorNumElements())); 9420 SubVecs[SVI].push_back(SubVec); 9421 } 9422 } 9423 9424 // Replace uses of the shufflevector instructions with the sub-vectors 9425 // returned by the load intrinsic. If a shufflevector instruction is 9426 // associated with more than one sub-vector, those sub-vectors will be 9427 // concatenated into a single wide vector. 9428 for (ShuffleVectorInst *SVI : Shuffles) { 9429 auto &SubVec = SubVecs[SVI]; 9430 auto *WideVec = 9431 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 9432 SVI->replaceAllUsesWith(WideVec); 9433 } 9434 9435 return true; 9436 } 9437 9438 /// Lower an interleaved store into a stN intrinsic. 9439 /// 9440 /// E.g. Lower an interleaved store (Factor = 3): 9441 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 9442 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 9443 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 9444 /// 9445 /// Into: 9446 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 9447 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 9448 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 9449 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 9450 /// 9451 /// Note that the new shufflevectors will be removed and we'll only generate one 9452 /// st3 instruction in CodeGen. 9453 /// 9454 /// Example for a more general valid mask (Factor 3). Lower: 9455 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 9456 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 9457 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 9458 /// 9459 /// Into: 9460 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 9461 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 9462 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 9463 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 9464 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI, 9465 ShuffleVectorInst *SVI, 9466 unsigned Factor) const { 9467 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 9468 "Invalid interleave factor"); 9469 9470 VectorType *VecTy = SVI->getType(); 9471 assert(VecTy->getVectorNumElements() % Factor == 0 && 9472 "Invalid interleaved store"); 9473 9474 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 9475 Type *EltTy = VecTy->getVectorElementType(); 9476 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 9477 9478 const DataLayout &DL = SI->getModule()->getDataLayout(); 9479 9480 // Skip if we do not have NEON and skip illegal vector types. We can 9481 // "legalize" wide vector types into multiple interleaved accesses as long as 9482 // the vector types are divisible by 128. 9483 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 9484 return false; 9485 9486 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 9487 9488 Value *Op0 = SVI->getOperand(0); 9489 Value *Op1 = SVI->getOperand(1); 9490 IRBuilder<> Builder(SI); 9491 9492 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 9493 // vectors to integer vectors. 9494 if (EltTy->isPointerTy()) { 9495 Type *IntTy = DL.getIntPtrType(EltTy); 9496 unsigned NumOpElts = Op0->getType()->getVectorNumElements(); 9497 9498 // Convert to the corresponding integer vector. 9499 Type *IntVecTy = VectorType::get(IntTy, NumOpElts); 9500 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 9501 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 9502 9503 SubVecTy = VectorType::get(IntTy, LaneLen); 9504 } 9505 9506 // The base address of the store. 9507 Value *BaseAddr = SI->getPointerOperand(); 9508 9509 if (NumStores > 1) { 9510 // If we're going to generate more than one store, reset the lane length 9511 // and sub-vector type to something legal. 9512 LaneLen /= NumStores; 9513 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 9514 9515 // We will compute the pointer operand of each store from the original base 9516 // address using GEPs. Cast the base address to a pointer to the scalar 9517 // element type. 9518 BaseAddr = Builder.CreateBitCast( 9519 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 9520 SI->getPointerAddressSpace())); 9521 } 9522 9523 auto Mask = SVI->getShuffleMask(); 9524 9525 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace()); 9526 Type *Tys[2] = {SubVecTy, PtrTy}; 9527 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2, 9528 Intrinsic::aarch64_neon_st3, 9529 Intrinsic::aarch64_neon_st4}; 9530 Function *StNFunc = 9531 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 9532 9533 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 9534 9535 SmallVector<Value *, 5> Ops; 9536 9537 // Split the shufflevector operands into sub vectors for the new stN call. 9538 for (unsigned i = 0; i < Factor; i++) { 9539 unsigned IdxI = StoreCount * LaneLen * Factor + i; 9540 if (Mask[IdxI] >= 0) { 9541 Ops.push_back(Builder.CreateShuffleVector( 9542 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 9543 } else { 9544 unsigned StartMask = 0; 9545 for (unsigned j = 1; j < LaneLen; j++) { 9546 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 9547 if (Mask[IdxJ * Factor + IdxI] >= 0) { 9548 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 9549 break; 9550 } 9551 } 9552 // Note: Filling undef gaps with random elements is ok, since 9553 // those elements were being written anyway (with undefs). 9554 // In the case of all undefs we're defaulting to using elems from 0 9555 // Note: StartMask cannot be negative, it's checked in 9556 // isReInterleaveMask 9557 Ops.push_back(Builder.CreateShuffleVector( 9558 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 9559 } 9560 } 9561 9562 // If we generating more than one store, we compute the base address of 9563 // subsequent stores as an offset from the previous. 9564 if (StoreCount > 0) 9565 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(), 9566 BaseAddr, LaneLen * Factor); 9567 9568 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy)); 9569 Builder.CreateCall(StNFunc, Ops); 9570 } 9571 return true; 9572 } 9573 9574 9575 EVT AArch64TargetLowering::getOptimalMemOpType( 9576 const MemOp &Op, const AttributeList &FuncAttributes) const { 9577 bool CanImplicitFloat = 9578 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat); 9579 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat; 9580 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat; 9581 // Only use AdvSIMD to implement memset of 32-byte and above. It would have 9582 // taken one instruction to materialize the v2i64 zero and one store (with 9583 // restrictive addressing mode). Just do i64 stores. 9584 bool IsSmallMemset = Op.isMemset() && Op.size() < 32; 9585 auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) { 9586 if (Op.isAligned(AlignCheck)) 9587 return true; 9588 bool Fast; 9589 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone, 9590 &Fast) && 9591 Fast; 9592 }; 9593 9594 if (CanUseNEON && Op.isMemset() && !IsSmallMemset && 9595 AlignmentIsAcceptable(MVT::v2i64, Align(16))) 9596 return MVT::v2i64; 9597 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16))) 9598 return MVT::f128; 9599 if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8))) 9600 return MVT::i64; 9601 if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4))) 9602 return MVT::i32; 9603 return MVT::Other; 9604 } 9605 9606 LLT AArch64TargetLowering::getOptimalMemOpLLT( 9607 const MemOp &Op, const AttributeList &FuncAttributes) const { 9608 bool CanImplicitFloat = 9609 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat); 9610 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat; 9611 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat; 9612 // Only use AdvSIMD to implement memset of 32-byte and above. It would have 9613 // taken one instruction to materialize the v2i64 zero and one store (with 9614 // restrictive addressing mode). Just do i64 stores. 9615 bool IsSmallMemset = Op.isMemset() && Op.size() < 32; 9616 auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) { 9617 if (Op.isAligned(AlignCheck)) 9618 return true; 9619 bool Fast; 9620 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone, 9621 &Fast) && 9622 Fast; 9623 }; 9624 9625 if (CanUseNEON && Op.isMemset() && !IsSmallMemset && 9626 AlignmentIsAcceptable(MVT::v2i64, Align(16))) 9627 return LLT::vector(2, 64); 9628 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16))) 9629 return LLT::scalar(128); 9630 if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8))) 9631 return LLT::scalar(64); 9632 if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4))) 9633 return LLT::scalar(32); 9634 return LLT(); 9635 } 9636 9637 // 12-bit optionally shifted immediates are legal for adds. 9638 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const { 9639 if (Immed == std::numeric_limits<int64_t>::min()) { 9640 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed 9641 << ": avoid UB for INT64_MIN\n"); 9642 return false; 9643 } 9644 // Same encoding for add/sub, just flip the sign. 9645 Immed = std::abs(Immed); 9646 bool IsLegal = ((Immed >> 12) == 0 || 9647 ((Immed & 0xfff) == 0 && Immed >> 24 == 0)); 9648 LLVM_DEBUG(dbgs() << "Is " << Immed 9649 << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n"); 9650 return IsLegal; 9651 } 9652 9653 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid 9654 // immediates is the same as for an add or a sub. 9655 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const { 9656 return isLegalAddImmediate(Immed); 9657 } 9658 9659 /// isLegalAddressingMode - Return true if the addressing mode represented 9660 /// by AM is legal for this target, for a load/store of the specified type. 9661 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL, 9662 const AddrMode &AM, Type *Ty, 9663 unsigned AS, Instruction *I) const { 9664 // AArch64 has five basic addressing modes: 9665 // reg 9666 // reg + 9-bit signed offset 9667 // reg + SIZE_IN_BYTES * 12-bit unsigned offset 9668 // reg1 + reg2 9669 // reg + SIZE_IN_BYTES * reg 9670 9671 // No global is ever allowed as a base. 9672 if (AM.BaseGV) 9673 return false; 9674 9675 // No reg+reg+imm addressing. 9676 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale) 9677 return false; 9678 9679 // FIXME: Update this method to support scalable addressing modes. 9680 if (Ty->isVectorTy() && Ty->getVectorIsScalable()) 9681 return AM.HasBaseReg && !AM.BaseOffs && !AM.Scale; 9682 9683 // check reg + imm case: 9684 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12 9685 uint64_t NumBytes = 0; 9686 if (Ty->isSized()) { 9687 uint64_t NumBits = DL.getTypeSizeInBits(Ty); 9688 NumBytes = NumBits / 8; 9689 if (!isPowerOf2_64(NumBits)) 9690 NumBytes = 0; 9691 } 9692 9693 if (!AM.Scale) { 9694 int64_t Offset = AM.BaseOffs; 9695 9696 // 9-bit signed offset 9697 if (isInt<9>(Offset)) 9698 return true; 9699 9700 // 12-bit unsigned offset 9701 unsigned shift = Log2_64(NumBytes); 9702 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 && 9703 // Must be a multiple of NumBytes (NumBytes is a power of 2) 9704 (Offset >> shift) << shift == Offset) 9705 return true; 9706 return false; 9707 } 9708 9709 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2 9710 9711 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes); 9712 } 9713 9714 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const { 9715 // Consider splitting large offset of struct or array. 9716 return true; 9717 } 9718 9719 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL, 9720 const AddrMode &AM, Type *Ty, 9721 unsigned AS) const { 9722 // Scaling factors are not free at all. 9723 // Operands | Rt Latency 9724 // ------------------------------------------- 9725 // Rt, [Xn, Xm] | 4 9726 // ------------------------------------------- 9727 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5 9728 // Rt, [Xn, Wm, <extend> #imm] | 9729 if (isLegalAddressingMode(DL, AM, Ty, AS)) 9730 // Scale represents reg2 * scale, thus account for 1 if 9731 // it is not equal to 0 or 1. 9732 return AM.Scale != 0 && AM.Scale != 1; 9733 return -1; 9734 } 9735 9736 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd( 9737 const MachineFunction &MF, EVT VT) const { 9738 VT = VT.getScalarType(); 9739 9740 if (!VT.isSimple()) 9741 return false; 9742 9743 switch (VT.getSimpleVT().SimpleTy) { 9744 case MVT::f32: 9745 case MVT::f64: 9746 return true; 9747 default: 9748 break; 9749 } 9750 9751 return false; 9752 } 9753 9754 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F, 9755 Type *Ty) const { 9756 switch (Ty->getScalarType()->getTypeID()) { 9757 case Type::FloatTyID: 9758 case Type::DoubleTyID: 9759 return true; 9760 default: 9761 return false; 9762 } 9763 } 9764 9765 const MCPhysReg * 9766 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const { 9767 // LR is a callee-save register, but we must treat it as clobbered by any call 9768 // site. Hence we include LR in the scratch registers, which are in turn added 9769 // as implicit-defs for stackmaps and patchpoints. 9770 static const MCPhysReg ScratchRegs[] = { 9771 AArch64::X16, AArch64::X17, AArch64::LR, 0 9772 }; 9773 return ScratchRegs; 9774 } 9775 9776 bool 9777 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N, 9778 CombineLevel Level) const { 9779 N = N->getOperand(0).getNode(); 9780 EVT VT = N->getValueType(0); 9781 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine 9782 // it with shift to let it be lowered to UBFX. 9783 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) && 9784 isa<ConstantSDNode>(N->getOperand(1))) { 9785 uint64_t TruncMask = N->getConstantOperandVal(1); 9786 if (isMask_64(TruncMask) && 9787 N->getOperand(0).getOpcode() == ISD::SRL && 9788 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1))) 9789 return false; 9790 } 9791 return true; 9792 } 9793 9794 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 9795 Type *Ty) const { 9796 assert(Ty->isIntegerTy()); 9797 9798 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 9799 if (BitSize == 0) 9800 return false; 9801 9802 int64_t Val = Imm.getSExtValue(); 9803 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize)) 9804 return true; 9805 9806 if ((int64_t)Val < 0) 9807 Val = ~Val; 9808 if (BitSize == 32) 9809 Val &= (1LL << 32) - 1; 9810 9811 unsigned LZ = countLeadingZeros((uint64_t)Val); 9812 unsigned Shift = (63 - LZ) / 16; 9813 // MOVZ is free so return true for one or fewer MOVK. 9814 return Shift < 3; 9815 } 9816 9817 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 9818 unsigned Index) const { 9819 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 9820 return false; 9821 9822 return (Index == 0 || Index == ResVT.getVectorNumElements()); 9823 } 9824 9825 /// Turn vector tests of the signbit in the form of: 9826 /// xor (sra X, elt_size(X)-1), -1 9827 /// into: 9828 /// cmge X, X, #0 9829 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG, 9830 const AArch64Subtarget *Subtarget) { 9831 EVT VT = N->getValueType(0); 9832 if (!Subtarget->hasNEON() || !VT.isVector()) 9833 return SDValue(); 9834 9835 // There must be a shift right algebraic before the xor, and the xor must be a 9836 // 'not' operation. 9837 SDValue Shift = N->getOperand(0); 9838 SDValue Ones = N->getOperand(1); 9839 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() || 9840 !ISD::isBuildVectorAllOnes(Ones.getNode())) 9841 return SDValue(); 9842 9843 // The shift should be smearing the sign bit across each vector element. 9844 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 9845 EVT ShiftEltTy = Shift.getValueType().getVectorElementType(); 9846 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1) 9847 return SDValue(); 9848 9849 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0)); 9850 } 9851 9852 // Generate SUBS and CSEL for integer abs. 9853 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) { 9854 EVT VT = N->getValueType(0); 9855 9856 SDValue N0 = N->getOperand(0); 9857 SDValue N1 = N->getOperand(1); 9858 SDLoc DL(N); 9859 9860 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1) 9861 // and change it to SUB and CSEL. 9862 if (VT.isInteger() && N->getOpcode() == ISD::XOR && 9863 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 && 9864 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0)) 9865 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1))) 9866 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) { 9867 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), 9868 N0.getOperand(0)); 9869 // Generate SUBS & CSEL. 9870 SDValue Cmp = 9871 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32), 9872 N0.getOperand(0), DAG.getConstant(0, DL, VT)); 9873 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg, 9874 DAG.getConstant(AArch64CC::PL, DL, MVT::i32), 9875 SDValue(Cmp.getNode(), 1)); 9876 } 9877 return SDValue(); 9878 } 9879 9880 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG, 9881 TargetLowering::DAGCombinerInfo &DCI, 9882 const AArch64Subtarget *Subtarget) { 9883 if (DCI.isBeforeLegalizeOps()) 9884 return SDValue(); 9885 9886 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget)) 9887 return Cmp; 9888 9889 return performIntegerAbsCombine(N, DAG); 9890 } 9891 9892 SDValue 9893 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 9894 SelectionDAG &DAG, 9895 SmallVectorImpl<SDNode *> &Created) const { 9896 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 9897 if (isIntDivCheap(N->getValueType(0), Attr)) 9898 return SDValue(N,0); // Lower SDIV as SDIV 9899 9900 // fold (sdiv X, pow2) 9901 EVT VT = N->getValueType(0); 9902 if ((VT != MVT::i32 && VT != MVT::i64) || 9903 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 9904 return SDValue(); 9905 9906 SDLoc DL(N); 9907 SDValue N0 = N->getOperand(0); 9908 unsigned Lg2 = Divisor.countTrailingZeros(); 9909 SDValue Zero = DAG.getConstant(0, DL, VT); 9910 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 9911 9912 // Add (N0 < 0) ? Pow2 - 1 : 0; 9913 SDValue CCVal; 9914 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL); 9915 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 9916 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp); 9917 9918 Created.push_back(Cmp.getNode()); 9919 Created.push_back(Add.getNode()); 9920 Created.push_back(CSel.getNode()); 9921 9922 // Divide by pow2. 9923 SDValue SRA = 9924 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64)); 9925 9926 // If we're dividing by a positive value, we're done. Otherwise, we must 9927 // negate the result. 9928 if (Divisor.isNonNegative()) 9929 return SRA; 9930 9931 Created.push_back(SRA.getNode()); 9932 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 9933 } 9934 9935 static bool IsSVECntIntrinsic(SDValue S) { 9936 switch(getIntrinsicID(S.getNode())) { 9937 default: 9938 break; 9939 case Intrinsic::aarch64_sve_cntb: 9940 case Intrinsic::aarch64_sve_cnth: 9941 case Intrinsic::aarch64_sve_cntw: 9942 case Intrinsic::aarch64_sve_cntd: 9943 return true; 9944 } 9945 return false; 9946 } 9947 9948 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG, 9949 TargetLowering::DAGCombinerInfo &DCI, 9950 const AArch64Subtarget *Subtarget) { 9951 if (DCI.isBeforeLegalizeOps()) 9952 return SDValue(); 9953 9954 // The below optimizations require a constant RHS. 9955 if (!isa<ConstantSDNode>(N->getOperand(1))) 9956 return SDValue(); 9957 9958 SDValue N0 = N->getOperand(0); 9959 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1)); 9960 const APInt &ConstValue = C->getAPIntValue(); 9961 9962 // Allow the scaling to be folded into the `cnt` instruction by preventing 9963 // the scaling to be obscured here. This makes it easier to pattern match. 9964 if (IsSVECntIntrinsic(N0) || 9965 (N0->getOpcode() == ISD::TRUNCATE && 9966 (IsSVECntIntrinsic(N0->getOperand(0))))) 9967 if (ConstValue.sge(1) && ConstValue.sle(16)) 9968 return SDValue(); 9969 9970 // Multiplication of a power of two plus/minus one can be done more 9971 // cheaply as as shift+add/sub. For now, this is true unilaterally. If 9972 // future CPUs have a cheaper MADD instruction, this may need to be 9973 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and 9974 // 64-bit is 5 cycles, so this is always a win. 9975 // More aggressively, some multiplications N0 * C can be lowered to 9976 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M, 9977 // e.g. 6=3*2=(2+1)*2. 9978 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45 9979 // which equals to (1+2)*16-(1+2). 9980 // TrailingZeroes is used to test if the mul can be lowered to 9981 // shift+add+shift. 9982 unsigned TrailingZeroes = ConstValue.countTrailingZeros(); 9983 if (TrailingZeroes) { 9984 // Conservatively do not lower to shift+add+shift if the mul might be 9985 // folded into smul or umul. 9986 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) || 9987 isZeroExtended(N0.getNode(), DAG))) 9988 return SDValue(); 9989 // Conservatively do not lower to shift+add+shift if the mul might be 9990 // folded into madd or msub. 9991 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD || 9992 N->use_begin()->getOpcode() == ISD::SUB)) 9993 return SDValue(); 9994 } 9995 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub 9996 // and shift+add+shift. 9997 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes); 9998 9999 unsigned ShiftAmt, AddSubOpc; 10000 // Is the shifted value the LHS operand of the add/sub? 10001 bool ShiftValUseIsN0 = true; 10002 // Do we need to negate the result? 10003 bool NegateResult = false; 10004 10005 if (ConstValue.isNonNegative()) { 10006 // (mul x, 2^N + 1) => (add (shl x, N), x) 10007 // (mul x, 2^N - 1) => (sub (shl x, N), x) 10008 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M) 10009 APInt SCVMinus1 = ShiftedConstValue - 1; 10010 APInt CVPlus1 = ConstValue + 1; 10011 if (SCVMinus1.isPowerOf2()) { 10012 ShiftAmt = SCVMinus1.logBase2(); 10013 AddSubOpc = ISD::ADD; 10014 } else if (CVPlus1.isPowerOf2()) { 10015 ShiftAmt = CVPlus1.logBase2(); 10016 AddSubOpc = ISD::SUB; 10017 } else 10018 return SDValue(); 10019 } else { 10020 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 10021 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 10022 APInt CVNegPlus1 = -ConstValue + 1; 10023 APInt CVNegMinus1 = -ConstValue - 1; 10024 if (CVNegPlus1.isPowerOf2()) { 10025 ShiftAmt = CVNegPlus1.logBase2(); 10026 AddSubOpc = ISD::SUB; 10027 ShiftValUseIsN0 = false; 10028 } else if (CVNegMinus1.isPowerOf2()) { 10029 ShiftAmt = CVNegMinus1.logBase2(); 10030 AddSubOpc = ISD::ADD; 10031 NegateResult = true; 10032 } else 10033 return SDValue(); 10034 } 10035 10036 SDLoc DL(N); 10037 EVT VT = N->getValueType(0); 10038 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0, 10039 DAG.getConstant(ShiftAmt, DL, MVT::i64)); 10040 10041 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0; 10042 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal; 10043 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1); 10044 assert(!(NegateResult && TrailingZeroes) && 10045 "NegateResult and TrailingZeroes cannot both be true for now."); 10046 // Negate the result. 10047 if (NegateResult) 10048 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 10049 // Shift the result. 10050 if (TrailingZeroes) 10051 return DAG.getNode(ISD::SHL, DL, VT, Res, 10052 DAG.getConstant(TrailingZeroes, DL, MVT::i64)); 10053 return Res; 10054 } 10055 10056 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N, 10057 SelectionDAG &DAG) { 10058 // Take advantage of vector comparisons producing 0 or -1 in each lane to 10059 // optimize away operation when it's from a constant. 10060 // 10061 // The general transformation is: 10062 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) --> 10063 // AND(VECTOR_CMP(x,y), constant2) 10064 // constant2 = UNARYOP(constant) 10065 10066 // Early exit if this isn't a vector operation, the operand of the 10067 // unary operation isn't a bitwise AND, or if the sizes of the operations 10068 // aren't the same. 10069 EVT VT = N->getValueType(0); 10070 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND || 10071 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC || 10072 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits()) 10073 return SDValue(); 10074 10075 // Now check that the other operand of the AND is a constant. We could 10076 // make the transformation for non-constant splats as well, but it's unclear 10077 // that would be a benefit as it would not eliminate any operations, just 10078 // perform one more step in scalar code before moving to the vector unit. 10079 if (BuildVectorSDNode *BV = 10080 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) { 10081 // Bail out if the vector isn't a constant. 10082 if (!BV->isConstant()) 10083 return SDValue(); 10084 10085 // Everything checks out. Build up the new and improved node. 10086 SDLoc DL(N); 10087 EVT IntVT = BV->getValueType(0); 10088 // Create a new constant of the appropriate type for the transformed 10089 // DAG. 10090 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0)); 10091 // The AND node needs bitcasts to/from an integer vector type around it. 10092 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst); 10093 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT, 10094 N->getOperand(0)->getOperand(0), MaskConst); 10095 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd); 10096 return Res; 10097 } 10098 10099 return SDValue(); 10100 } 10101 10102 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG, 10103 const AArch64Subtarget *Subtarget) { 10104 // First try to optimize away the conversion when it's conditionally from 10105 // a constant. Vectors only. 10106 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG)) 10107 return Res; 10108 10109 EVT VT = N->getValueType(0); 10110 if (VT != MVT::f32 && VT != MVT::f64) 10111 return SDValue(); 10112 10113 // Only optimize when the source and destination types have the same width. 10114 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits()) 10115 return SDValue(); 10116 10117 // If the result of an integer load is only used by an integer-to-float 10118 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead. 10119 // This eliminates an "integer-to-vector-move" UOP and improves throughput. 10120 SDValue N0 = N->getOperand(0); 10121 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 10122 // Do not change the width of a volatile load. 10123 !cast<LoadSDNode>(N0)->isVolatile()) { 10124 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 10125 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 10126 LN0->getPointerInfo(), LN0->getAlignment(), 10127 LN0->getMemOperand()->getFlags()); 10128 10129 // Make sure successors of the original load stay after it by updating them 10130 // to use the new Chain. 10131 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1)); 10132 10133 unsigned Opcode = 10134 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF; 10135 return DAG.getNode(Opcode, SDLoc(N), VT, Load); 10136 } 10137 10138 return SDValue(); 10139 } 10140 10141 /// Fold a floating-point multiply by power of two into floating-point to 10142 /// fixed-point conversion. 10143 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG, 10144 TargetLowering::DAGCombinerInfo &DCI, 10145 const AArch64Subtarget *Subtarget) { 10146 if (!Subtarget->hasNEON()) 10147 return SDValue(); 10148 10149 if (!N->getValueType(0).isSimple()) 10150 return SDValue(); 10151 10152 SDValue Op = N->getOperand(0); 10153 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 10154 Op.getOpcode() != ISD::FMUL) 10155 return SDValue(); 10156 10157 SDValue ConstVec = Op->getOperand(1); 10158 if (!isa<BuildVectorSDNode>(ConstVec)) 10159 return SDValue(); 10160 10161 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 10162 uint32_t FloatBits = FloatTy.getSizeInBits(); 10163 if (FloatBits != 32 && FloatBits != 64) 10164 return SDValue(); 10165 10166 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 10167 uint32_t IntBits = IntTy.getSizeInBits(); 10168 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 10169 return SDValue(); 10170 10171 // Avoid conversions where iN is larger than the float (e.g., float -> i64). 10172 if (IntBits > FloatBits) 10173 return SDValue(); 10174 10175 BitVector UndefElements; 10176 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10177 int32_t Bits = IntBits == 64 ? 64 : 32; 10178 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1); 10179 if (C == -1 || C == 0 || C > Bits) 10180 return SDValue(); 10181 10182 MVT ResTy; 10183 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10184 switch (NumLanes) { 10185 default: 10186 return SDValue(); 10187 case 2: 10188 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 10189 break; 10190 case 4: 10191 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; 10192 break; 10193 } 10194 10195 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) 10196 return SDValue(); 10197 10198 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) && 10199 "Illegal vector type after legalization"); 10200 10201 SDLoc DL(N); 10202 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 10203 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs 10204 : Intrinsic::aarch64_neon_vcvtfp2fxu; 10205 SDValue FixConv = 10206 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy, 10207 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), 10208 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32)); 10209 // We can handle smaller integers by generating an extra trunc. 10210 if (IntBits < FloatBits) 10211 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv); 10212 10213 return FixConv; 10214 } 10215 10216 /// Fold a floating-point divide by power of two into fixed-point to 10217 /// floating-point conversion. 10218 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG, 10219 TargetLowering::DAGCombinerInfo &DCI, 10220 const AArch64Subtarget *Subtarget) { 10221 if (!Subtarget->hasNEON()) 10222 return SDValue(); 10223 10224 SDValue Op = N->getOperand(0); 10225 unsigned Opc = Op->getOpcode(); 10226 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 10227 !Op.getOperand(0).getValueType().isSimple() || 10228 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP)) 10229 return SDValue(); 10230 10231 SDValue ConstVec = N->getOperand(1); 10232 if (!isa<BuildVectorSDNode>(ConstVec)) 10233 return SDValue(); 10234 10235 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 10236 int32_t IntBits = IntTy.getSizeInBits(); 10237 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 10238 return SDValue(); 10239 10240 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 10241 int32_t FloatBits = FloatTy.getSizeInBits(); 10242 if (FloatBits != 32 && FloatBits != 64) 10243 return SDValue(); 10244 10245 // Avoid conversions where iN is larger than the float (e.g., i64 -> float). 10246 if (IntBits > FloatBits) 10247 return SDValue(); 10248 10249 BitVector UndefElements; 10250 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 10251 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1); 10252 if (C == -1 || C == 0 || C > FloatBits) 10253 return SDValue(); 10254 10255 MVT ResTy; 10256 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 10257 switch (NumLanes) { 10258 default: 10259 return SDValue(); 10260 case 2: 10261 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 10262 break; 10263 case 4: 10264 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; 10265 break; 10266 } 10267 10268 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) 10269 return SDValue(); 10270 10271 SDLoc DL(N); 10272 SDValue ConvInput = Op.getOperand(0); 10273 bool IsSigned = Opc == ISD::SINT_TO_FP; 10274 if (IntBits < FloatBits) 10275 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, 10276 ResTy, ConvInput); 10277 10278 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp 10279 : Intrinsic::aarch64_neon_vcvtfxu2fp; 10280 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(), 10281 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput, 10282 DAG.getConstant(C, DL, MVT::i32)); 10283 } 10284 10285 /// An EXTR instruction is made up of two shifts, ORed together. This helper 10286 /// searches for and classifies those shifts. 10287 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount, 10288 bool &FromHi) { 10289 if (N.getOpcode() == ISD::SHL) 10290 FromHi = false; 10291 else if (N.getOpcode() == ISD::SRL) 10292 FromHi = true; 10293 else 10294 return false; 10295 10296 if (!isa<ConstantSDNode>(N.getOperand(1))) 10297 return false; 10298 10299 ShiftAmount = N->getConstantOperandVal(1); 10300 Src = N->getOperand(0); 10301 return true; 10302 } 10303 10304 /// EXTR instruction extracts a contiguous chunk of bits from two existing 10305 /// registers viewed as a high/low pair. This function looks for the pattern: 10306 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it 10307 /// with an EXTR. Can't quite be done in TableGen because the two immediates 10308 /// aren't independent. 10309 static SDValue tryCombineToEXTR(SDNode *N, 10310 TargetLowering::DAGCombinerInfo &DCI) { 10311 SelectionDAG &DAG = DCI.DAG; 10312 SDLoc DL(N); 10313 EVT VT = N->getValueType(0); 10314 10315 assert(N->getOpcode() == ISD::OR && "Unexpected root"); 10316 10317 if (VT != MVT::i32 && VT != MVT::i64) 10318 return SDValue(); 10319 10320 SDValue LHS; 10321 uint32_t ShiftLHS = 0; 10322 bool LHSFromHi = false; 10323 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi)) 10324 return SDValue(); 10325 10326 SDValue RHS; 10327 uint32_t ShiftRHS = 0; 10328 bool RHSFromHi = false; 10329 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi)) 10330 return SDValue(); 10331 10332 // If they're both trying to come from the high part of the register, they're 10333 // not really an EXTR. 10334 if (LHSFromHi == RHSFromHi) 10335 return SDValue(); 10336 10337 if (ShiftLHS + ShiftRHS != VT.getSizeInBits()) 10338 return SDValue(); 10339 10340 if (LHSFromHi) { 10341 std::swap(LHS, RHS); 10342 std::swap(ShiftLHS, ShiftRHS); 10343 } 10344 10345 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS, 10346 DAG.getConstant(ShiftRHS, DL, MVT::i64)); 10347 } 10348 10349 static SDValue tryCombineToBSL(SDNode *N, 10350 TargetLowering::DAGCombinerInfo &DCI) { 10351 EVT VT = N->getValueType(0); 10352 SelectionDAG &DAG = DCI.DAG; 10353 SDLoc DL(N); 10354 10355 if (!VT.isVector()) 10356 return SDValue(); 10357 10358 SDValue N0 = N->getOperand(0); 10359 if (N0.getOpcode() != ISD::AND) 10360 return SDValue(); 10361 10362 SDValue N1 = N->getOperand(1); 10363 if (N1.getOpcode() != ISD::AND) 10364 return SDValue(); 10365 10366 // We only have to look for constant vectors here since the general, variable 10367 // case can be handled in TableGen. 10368 unsigned Bits = VT.getScalarSizeInBits(); 10369 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1); 10370 for (int i = 1; i >= 0; --i) 10371 for (int j = 1; j >= 0; --j) { 10372 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i)); 10373 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j)); 10374 if (!BVN0 || !BVN1) 10375 continue; 10376 10377 bool FoundMatch = true; 10378 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) { 10379 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k)); 10380 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k)); 10381 if (!CN0 || !CN1 || 10382 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) { 10383 FoundMatch = false; 10384 break; 10385 } 10386 } 10387 10388 if (FoundMatch) 10389 return DAG.getNode(AArch64ISD::BSP, DL, VT, SDValue(BVN0, 0), 10390 N0->getOperand(1 - i), N1->getOperand(1 - j)); 10391 } 10392 10393 return SDValue(); 10394 } 10395 10396 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 10397 const AArch64Subtarget *Subtarget) { 10398 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) 10399 SelectionDAG &DAG = DCI.DAG; 10400 EVT VT = N->getValueType(0); 10401 10402 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10403 return SDValue(); 10404 10405 if (SDValue Res = tryCombineToEXTR(N, DCI)) 10406 return Res; 10407 10408 if (SDValue Res = tryCombineToBSL(N, DCI)) 10409 return Res; 10410 10411 return SDValue(); 10412 } 10413 10414 static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) { 10415 if (!MemVT.getVectorElementType().isSimple()) 10416 return false; 10417 10418 uint64_t MaskForTy = 0ull; 10419 switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) { 10420 case MVT::i8: 10421 MaskForTy = 0xffull; 10422 break; 10423 case MVT::i16: 10424 MaskForTy = 0xffffull; 10425 break; 10426 case MVT::i32: 10427 MaskForTy = 0xffffffffull; 10428 break; 10429 default: 10430 return false; 10431 break; 10432 } 10433 10434 if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR) 10435 if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0))) 10436 return Op0->getAPIntValue().getLimitedValue() == MaskForTy; 10437 10438 return false; 10439 } 10440 10441 static SDValue performSVEAndCombine(SDNode *N, 10442 TargetLowering::DAGCombinerInfo &DCI) { 10443 if (DCI.isBeforeLegalizeOps()) 10444 return SDValue(); 10445 10446 SDValue Src = N->getOperand(0); 10447 SDValue Mask = N->getOperand(1); 10448 10449 if (!Src.hasOneUse()) 10450 return SDValue(); 10451 10452 EVT MemVT; 10453 10454 // SVE load instructions perform an implicit zero-extend, which makes them 10455 // perfect candidates for combining. 10456 switch (Src->getOpcode()) { 10457 case AArch64ISD::LDNF1: 10458 case AArch64ISD::LDFF1: 10459 MemVT = cast<VTSDNode>(Src->getOperand(3))->getVT(); 10460 break; 10461 case AArch64ISD::GLD1: 10462 case AArch64ISD::GLD1_SCALED: 10463 case AArch64ISD::GLD1_SXTW: 10464 case AArch64ISD::GLD1_SXTW_SCALED: 10465 case AArch64ISD::GLD1_UXTW: 10466 case AArch64ISD::GLD1_UXTW_SCALED: 10467 case AArch64ISD::GLD1_IMM: 10468 case AArch64ISD::GLDFF1: 10469 case AArch64ISD::GLDFF1_SCALED: 10470 case AArch64ISD::GLDFF1_SXTW: 10471 case AArch64ISD::GLDFF1_SXTW_SCALED: 10472 case AArch64ISD::GLDFF1_UXTW: 10473 case AArch64ISD::GLDFF1_UXTW_SCALED: 10474 case AArch64ISD::GLDFF1_IMM: 10475 case AArch64ISD::GLDNT1: 10476 MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT(); 10477 break; 10478 default: 10479 return SDValue(); 10480 } 10481 10482 if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT)) 10483 return Src; 10484 10485 return SDValue(); 10486 } 10487 10488 static SDValue performANDCombine(SDNode *N, 10489 TargetLowering::DAGCombinerInfo &DCI) { 10490 SelectionDAG &DAG = DCI.DAG; 10491 SDValue LHS = N->getOperand(0); 10492 EVT VT = N->getValueType(0); 10493 if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT)) 10494 return SDValue(); 10495 10496 if (VT.isScalableVector()) 10497 return performSVEAndCombine(N, DCI); 10498 10499 BuildVectorSDNode *BVN = 10500 dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode()); 10501 if (!BVN) 10502 return SDValue(); 10503 10504 // AND does not accept an immediate, so check if we can use a BIC immediate 10505 // instruction instead. We do this here instead of using a (and x, (mvni imm)) 10506 // pattern in isel, because some immediates may be lowered to the preferred 10507 // (and x, (movi imm)) form, even though an mvni representation also exists. 10508 APInt DefBits(VT.getSizeInBits(), 0); 10509 APInt UndefBits(VT.getSizeInBits(), 0); 10510 if (resolveBuildVector(BVN, DefBits, UndefBits)) { 10511 SDValue NewOp; 10512 10513 DefBits = ~DefBits; 10514 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG, 10515 DefBits, &LHS)) || 10516 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG, 10517 DefBits, &LHS))) 10518 return NewOp; 10519 10520 UndefBits = ~UndefBits; 10521 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG, 10522 UndefBits, &LHS)) || 10523 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG, 10524 UndefBits, &LHS))) 10525 return NewOp; 10526 } 10527 10528 return SDValue(); 10529 } 10530 10531 static SDValue performSRLCombine(SDNode *N, 10532 TargetLowering::DAGCombinerInfo &DCI) { 10533 SelectionDAG &DAG = DCI.DAG; 10534 EVT VT = N->getValueType(0); 10535 if (VT != MVT::i32 && VT != MVT::i64) 10536 return SDValue(); 10537 10538 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the 10539 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32) 10540 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero. 10541 SDValue N0 = N->getOperand(0); 10542 if (N0.getOpcode() == ISD::BSWAP) { 10543 SDLoc DL(N); 10544 SDValue N1 = N->getOperand(1); 10545 SDValue N00 = N0.getOperand(0); 10546 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 10547 uint64_t ShiftAmt = C->getZExtValue(); 10548 if (VT == MVT::i32 && ShiftAmt == 16 && 10549 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16))) 10550 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 10551 if (VT == MVT::i64 && ShiftAmt == 32 && 10552 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32))) 10553 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 10554 } 10555 } 10556 return SDValue(); 10557 } 10558 10559 static SDValue performConcatVectorsCombine(SDNode *N, 10560 TargetLowering::DAGCombinerInfo &DCI, 10561 SelectionDAG &DAG) { 10562 SDLoc dl(N); 10563 EVT VT = N->getValueType(0); 10564 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 10565 10566 // Optimize concat_vectors of truncated vectors, where the intermediate 10567 // type is illegal, to avoid said illegality, e.g., 10568 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))), 10569 // (v2i16 (truncate (v2i64))))) 10570 // -> 10571 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))), 10572 // (v4i32 (bitcast (v2i64))), 10573 // <0, 2, 4, 6>))) 10574 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed 10575 // on both input and result type, so we might generate worse code. 10576 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8. 10577 if (N->getNumOperands() == 2 && 10578 N0->getOpcode() == ISD::TRUNCATE && 10579 N1->getOpcode() == ISD::TRUNCATE) { 10580 SDValue N00 = N0->getOperand(0); 10581 SDValue N10 = N1->getOperand(0); 10582 EVT N00VT = N00.getValueType(); 10583 10584 if (N00VT == N10.getValueType() && 10585 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) && 10586 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) { 10587 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16); 10588 SmallVector<int, 8> Mask(MidVT.getVectorNumElements()); 10589 for (size_t i = 0; i < Mask.size(); ++i) 10590 Mask[i] = i * 2; 10591 return DAG.getNode(ISD::TRUNCATE, dl, VT, 10592 DAG.getVectorShuffle( 10593 MidVT, dl, 10594 DAG.getNode(ISD::BITCAST, dl, MidVT, N00), 10595 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask)); 10596 } 10597 } 10598 10599 // Wait 'til after everything is legalized to try this. That way we have 10600 // legal vector types and such. 10601 if (DCI.isBeforeLegalizeOps()) 10602 return SDValue(); 10603 10604 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector 10605 // splat. The indexed instructions are going to be expecting a DUPLANE64, so 10606 // canonicalise to that. 10607 if (N0 == N1 && VT.getVectorNumElements() == 2) { 10608 assert(VT.getScalarSizeInBits() == 64); 10609 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG), 10610 DAG.getConstant(0, dl, MVT::i64)); 10611 } 10612 10613 // Canonicalise concat_vectors so that the right-hand vector has as few 10614 // bit-casts as possible before its real operation. The primary matching 10615 // destination for these operations will be the narrowing "2" instructions, 10616 // which depend on the operation being performed on this right-hand vector. 10617 // For example, 10618 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS)))) 10619 // becomes 10620 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS)) 10621 10622 if (N1->getOpcode() != ISD::BITCAST) 10623 return SDValue(); 10624 SDValue RHS = N1->getOperand(0); 10625 MVT RHSTy = RHS.getValueType().getSimpleVT(); 10626 // If the RHS is not a vector, this is not the pattern we're looking for. 10627 if (!RHSTy.isVector()) 10628 return SDValue(); 10629 10630 LLVM_DEBUG( 10631 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n"); 10632 10633 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(), 10634 RHSTy.getVectorNumElements() * 2); 10635 return DAG.getNode(ISD::BITCAST, dl, VT, 10636 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy, 10637 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0), 10638 RHS)); 10639 } 10640 10641 static SDValue tryCombineFixedPointConvert(SDNode *N, 10642 TargetLowering::DAGCombinerInfo &DCI, 10643 SelectionDAG &DAG) { 10644 // Wait until after everything is legalized to try this. That way we have 10645 // legal vector types and such. 10646 if (DCI.isBeforeLegalizeOps()) 10647 return SDValue(); 10648 // Transform a scalar conversion of a value from a lane extract into a 10649 // lane extract of a vector conversion. E.g., from foo1 to foo2: 10650 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); } 10651 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; } 10652 // 10653 // The second form interacts better with instruction selection and the 10654 // register allocator to avoid cross-class register copies that aren't 10655 // coalescable due to a lane reference. 10656 10657 // Check the operand and see if it originates from a lane extract. 10658 SDValue Op1 = N->getOperand(1); 10659 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 10660 // Yep, no additional predication needed. Perform the transform. 10661 SDValue IID = N->getOperand(0); 10662 SDValue Shift = N->getOperand(2); 10663 SDValue Vec = Op1.getOperand(0); 10664 SDValue Lane = Op1.getOperand(1); 10665 EVT ResTy = N->getValueType(0); 10666 EVT VecResTy; 10667 SDLoc DL(N); 10668 10669 // The vector width should be 128 bits by the time we get here, even 10670 // if it started as 64 bits (the extract_vector handling will have 10671 // done so). 10672 assert(Vec.getValueSizeInBits() == 128 && 10673 "unexpected vector size on extract_vector_elt!"); 10674 if (Vec.getValueType() == MVT::v4i32) 10675 VecResTy = MVT::v4f32; 10676 else if (Vec.getValueType() == MVT::v2i64) 10677 VecResTy = MVT::v2f64; 10678 else 10679 llvm_unreachable("unexpected vector type!"); 10680 10681 SDValue Convert = 10682 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift); 10683 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane); 10684 } 10685 return SDValue(); 10686 } 10687 10688 // AArch64 high-vector "long" operations are formed by performing the non-high 10689 // version on an extract_subvector of each operand which gets the high half: 10690 // 10691 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS)) 10692 // 10693 // However, there are cases which don't have an extract_high explicitly, but 10694 // have another operation that can be made compatible with one for free. For 10695 // example: 10696 // 10697 // (dupv64 scalar) --> (extract_high (dup128 scalar)) 10698 // 10699 // This routine does the actual conversion of such DUPs, once outer routines 10700 // have determined that everything else is in order. 10701 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold 10702 // similarly here. 10703 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) { 10704 switch (N.getOpcode()) { 10705 case AArch64ISD::DUP: 10706 case AArch64ISD::DUPLANE8: 10707 case AArch64ISD::DUPLANE16: 10708 case AArch64ISD::DUPLANE32: 10709 case AArch64ISD::DUPLANE64: 10710 case AArch64ISD::MOVI: 10711 case AArch64ISD::MOVIshift: 10712 case AArch64ISD::MOVIedit: 10713 case AArch64ISD::MOVImsl: 10714 case AArch64ISD::MVNIshift: 10715 case AArch64ISD::MVNImsl: 10716 break; 10717 default: 10718 // FMOV could be supported, but isn't very useful, as it would only occur 10719 // if you passed a bitcast' floating point immediate to an eligible long 10720 // integer op (addl, smull, ...). 10721 return SDValue(); 10722 } 10723 10724 MVT NarrowTy = N.getSimpleValueType(); 10725 if (!NarrowTy.is64BitVector()) 10726 return SDValue(); 10727 10728 MVT ElementTy = NarrowTy.getVectorElementType(); 10729 unsigned NumElems = NarrowTy.getVectorNumElements(); 10730 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2); 10731 10732 SDLoc dl(N); 10733 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy, 10734 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()), 10735 DAG.getConstant(NumElems, dl, MVT::i64)); 10736 } 10737 10738 static bool isEssentiallyExtractHighSubvector(SDValue N) { 10739 if (N.getOpcode() == ISD::BITCAST) 10740 N = N.getOperand(0); 10741 if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR) 10742 return false; 10743 return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() == 10744 N.getOperand(0).getValueType().getVectorNumElements() / 2; 10745 } 10746 10747 /// Helper structure to keep track of ISD::SET_CC operands. 10748 struct GenericSetCCInfo { 10749 const SDValue *Opnd0; 10750 const SDValue *Opnd1; 10751 ISD::CondCode CC; 10752 }; 10753 10754 /// Helper structure to keep track of a SET_CC lowered into AArch64 code. 10755 struct AArch64SetCCInfo { 10756 const SDValue *Cmp; 10757 AArch64CC::CondCode CC; 10758 }; 10759 10760 /// Helper structure to keep track of SetCC information. 10761 union SetCCInfo { 10762 GenericSetCCInfo Generic; 10763 AArch64SetCCInfo AArch64; 10764 }; 10765 10766 /// Helper structure to be able to read SetCC information. If set to 10767 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a 10768 /// GenericSetCCInfo. 10769 struct SetCCInfoAndKind { 10770 SetCCInfo Info; 10771 bool IsAArch64; 10772 }; 10773 10774 /// Check whether or not \p Op is a SET_CC operation, either a generic or 10775 /// an 10776 /// AArch64 lowered one. 10777 /// \p SetCCInfo is filled accordingly. 10778 /// \post SetCCInfo is meanginfull only when this function returns true. 10779 /// \return True when Op is a kind of SET_CC operation. 10780 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) { 10781 // If this is a setcc, this is straight forward. 10782 if (Op.getOpcode() == ISD::SETCC) { 10783 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0); 10784 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1); 10785 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 10786 SetCCInfo.IsAArch64 = false; 10787 return true; 10788 } 10789 // Otherwise, check if this is a matching csel instruction. 10790 // In other words: 10791 // - csel 1, 0, cc 10792 // - csel 0, 1, !cc 10793 if (Op.getOpcode() != AArch64ISD::CSEL) 10794 return false; 10795 // Set the information about the operands. 10796 // TODO: we want the operands of the Cmp not the csel 10797 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3); 10798 SetCCInfo.IsAArch64 = true; 10799 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>( 10800 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); 10801 10802 // Check that the operands matches the constraints: 10803 // (1) Both operands must be constants. 10804 // (2) One must be 1 and the other must be 0. 10805 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0)); 10806 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 10807 10808 // Check (1). 10809 if (!TValue || !FValue) 10810 return false; 10811 10812 // Check (2). 10813 if (!TValue->isOne()) { 10814 // Update the comparison when we are interested in !cc. 10815 std::swap(TValue, FValue); 10816 SetCCInfo.Info.AArch64.CC = 10817 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC); 10818 } 10819 return TValue->isOne() && FValue->isNullValue(); 10820 } 10821 10822 // Returns true if Op is setcc or zext of setcc. 10823 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) { 10824 if (isSetCC(Op, Info)) 10825 return true; 10826 return ((Op.getOpcode() == ISD::ZERO_EXTEND) && 10827 isSetCC(Op->getOperand(0), Info)); 10828 } 10829 10830 // The folding we want to perform is: 10831 // (add x, [zext] (setcc cc ...) ) 10832 // --> 10833 // (csel x, (add x, 1), !cc ...) 10834 // 10835 // The latter will get matched to a CSINC instruction. 10836 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) { 10837 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!"); 10838 SDValue LHS = Op->getOperand(0); 10839 SDValue RHS = Op->getOperand(1); 10840 SetCCInfoAndKind InfoAndKind; 10841 10842 // If neither operand is a SET_CC, give up. 10843 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) { 10844 std::swap(LHS, RHS); 10845 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) 10846 return SDValue(); 10847 } 10848 10849 // FIXME: This could be generatized to work for FP comparisons. 10850 EVT CmpVT = InfoAndKind.IsAArch64 10851 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType() 10852 : InfoAndKind.Info.Generic.Opnd0->getValueType(); 10853 if (CmpVT != MVT::i32 && CmpVT != MVT::i64) 10854 return SDValue(); 10855 10856 SDValue CCVal; 10857 SDValue Cmp; 10858 SDLoc dl(Op); 10859 if (InfoAndKind.IsAArch64) { 10860 CCVal = DAG.getConstant( 10861 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl, 10862 MVT::i32); 10863 Cmp = *InfoAndKind.Info.AArch64.Cmp; 10864 } else 10865 Cmp = getAArch64Cmp( 10866 *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1, 10867 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG, 10868 dl); 10869 10870 EVT VT = Op->getValueType(0); 10871 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT)); 10872 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp); 10873 } 10874 10875 // The basic add/sub long vector instructions have variants with "2" on the end 10876 // which act on the high-half of their inputs. They are normally matched by 10877 // patterns like: 10878 // 10879 // (add (zeroext (extract_high LHS)), 10880 // (zeroext (extract_high RHS))) 10881 // -> uaddl2 vD, vN, vM 10882 // 10883 // However, if one of the extracts is something like a duplicate, this 10884 // instruction can still be used profitably. This function puts the DAG into a 10885 // more appropriate form for those patterns to trigger. 10886 static SDValue performAddSubLongCombine(SDNode *N, 10887 TargetLowering::DAGCombinerInfo &DCI, 10888 SelectionDAG &DAG) { 10889 if (DCI.isBeforeLegalizeOps()) 10890 return SDValue(); 10891 10892 MVT VT = N->getSimpleValueType(0); 10893 if (!VT.is128BitVector()) { 10894 if (N->getOpcode() == ISD::ADD) 10895 return performSetccAddFolding(N, DAG); 10896 return SDValue(); 10897 } 10898 10899 // Make sure both branches are extended in the same way. 10900 SDValue LHS = N->getOperand(0); 10901 SDValue RHS = N->getOperand(1); 10902 if ((LHS.getOpcode() != ISD::ZERO_EXTEND && 10903 LHS.getOpcode() != ISD::SIGN_EXTEND) || 10904 LHS.getOpcode() != RHS.getOpcode()) 10905 return SDValue(); 10906 10907 unsigned ExtType = LHS.getOpcode(); 10908 10909 // It's not worth doing if at least one of the inputs isn't already an 10910 // extract, but we don't know which it'll be so we have to try both. 10911 if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) { 10912 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG); 10913 if (!RHS.getNode()) 10914 return SDValue(); 10915 10916 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS); 10917 } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) { 10918 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG); 10919 if (!LHS.getNode()) 10920 return SDValue(); 10921 10922 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS); 10923 } 10924 10925 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS); 10926 } 10927 10928 // Massage DAGs which we can use the high-half "long" operations on into 10929 // something isel will recognize better. E.g. 10930 // 10931 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) --> 10932 // (aarch64_neon_umull (extract_high (v2i64 vec))) 10933 // (extract_high (v2i64 (dup128 scalar))))) 10934 // 10935 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N, 10936 TargetLowering::DAGCombinerInfo &DCI, 10937 SelectionDAG &DAG) { 10938 if (DCI.isBeforeLegalizeOps()) 10939 return SDValue(); 10940 10941 SDValue LHS = N->getOperand(1); 10942 SDValue RHS = N->getOperand(2); 10943 assert(LHS.getValueType().is64BitVector() && 10944 RHS.getValueType().is64BitVector() && 10945 "unexpected shape for long operation"); 10946 10947 // Either node could be a DUP, but it's not worth doing both of them (you'd 10948 // just as well use the non-high version) so look for a corresponding extract 10949 // operation on the other "wing". 10950 if (isEssentiallyExtractHighSubvector(LHS)) { 10951 RHS = tryExtendDUPToExtractHigh(RHS, DAG); 10952 if (!RHS.getNode()) 10953 return SDValue(); 10954 } else if (isEssentiallyExtractHighSubvector(RHS)) { 10955 LHS = tryExtendDUPToExtractHigh(LHS, DAG); 10956 if (!LHS.getNode()) 10957 return SDValue(); 10958 } 10959 10960 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0), 10961 N->getOperand(0), LHS, RHS); 10962 } 10963 10964 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) { 10965 MVT ElemTy = N->getSimpleValueType(0).getScalarType(); 10966 unsigned ElemBits = ElemTy.getSizeInBits(); 10967 10968 int64_t ShiftAmount; 10969 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) { 10970 APInt SplatValue, SplatUndef; 10971 unsigned SplatBitSize; 10972 bool HasAnyUndefs; 10973 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 10974 HasAnyUndefs, ElemBits) || 10975 SplatBitSize != ElemBits) 10976 return SDValue(); 10977 10978 ShiftAmount = SplatValue.getSExtValue(); 10979 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) { 10980 ShiftAmount = CVN->getSExtValue(); 10981 } else 10982 return SDValue(); 10983 10984 unsigned Opcode; 10985 bool IsRightShift; 10986 switch (IID) { 10987 default: 10988 llvm_unreachable("Unknown shift intrinsic"); 10989 case Intrinsic::aarch64_neon_sqshl: 10990 Opcode = AArch64ISD::SQSHL_I; 10991 IsRightShift = false; 10992 break; 10993 case Intrinsic::aarch64_neon_uqshl: 10994 Opcode = AArch64ISD::UQSHL_I; 10995 IsRightShift = false; 10996 break; 10997 case Intrinsic::aarch64_neon_srshl: 10998 Opcode = AArch64ISD::SRSHR_I; 10999 IsRightShift = true; 11000 break; 11001 case Intrinsic::aarch64_neon_urshl: 11002 Opcode = AArch64ISD::URSHR_I; 11003 IsRightShift = true; 11004 break; 11005 case Intrinsic::aarch64_neon_sqshlu: 11006 Opcode = AArch64ISD::SQSHLU_I; 11007 IsRightShift = false; 11008 break; 11009 case Intrinsic::aarch64_neon_sshl: 11010 case Intrinsic::aarch64_neon_ushl: 11011 // For positive shift amounts we can use SHL, as ushl/sshl perform a regular 11012 // left shift for positive shift amounts. Below, we only replace the current 11013 // node with VSHL, if this condition is met. 11014 Opcode = AArch64ISD::VSHL; 11015 IsRightShift = false; 11016 break; 11017 } 11018 11019 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) { 11020 SDLoc dl(N); 11021 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 11022 DAG.getConstant(-ShiftAmount, dl, MVT::i32)); 11023 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) { 11024 SDLoc dl(N); 11025 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 11026 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 11027 } 11028 11029 return SDValue(); 11030 } 11031 11032 // The CRC32[BH] instructions ignore the high bits of their data operand. Since 11033 // the intrinsics must be legal and take an i32, this means there's almost 11034 // certainly going to be a zext in the DAG which we can eliminate. 11035 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) { 11036 SDValue AndN = N->getOperand(2); 11037 if (AndN.getOpcode() != ISD::AND) 11038 return SDValue(); 11039 11040 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1)); 11041 if (!CMask || CMask->getZExtValue() != Mask) 11042 return SDValue(); 11043 11044 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32, 11045 N->getOperand(0), N->getOperand(1), AndN.getOperand(0)); 11046 } 11047 11048 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N, 11049 SelectionDAG &DAG) { 11050 SDLoc dl(N); 11051 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), 11052 DAG.getNode(Opc, dl, 11053 N->getOperand(1).getSimpleValueType(), 11054 N->getOperand(1)), 11055 DAG.getConstant(0, dl, MVT::i64)); 11056 } 11057 11058 static SDValue LowerSVEIntReduction(SDNode *N, unsigned Opc, 11059 SelectionDAG &DAG) { 11060 SDLoc dl(N); 11061 LLVMContext &Ctx = *DAG.getContext(); 11062 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11063 11064 EVT VT = N->getValueType(0); 11065 SDValue Pred = N->getOperand(1); 11066 SDValue Data = N->getOperand(2); 11067 EVT DataVT = Data.getValueType(); 11068 11069 if (DataVT.getVectorElementType().isScalarInteger() && 11070 (VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32 || VT == MVT::i64)) { 11071 if (!TLI.isTypeLegal(DataVT)) 11072 return SDValue(); 11073 11074 EVT OutputVT = EVT::getVectorVT(Ctx, VT, 11075 AArch64::NeonBitsPerVector / VT.getSizeInBits()); 11076 SDValue Reduce = DAG.getNode(Opc, dl, OutputVT, Pred, Data); 11077 SDValue Zero = DAG.getConstant(0, dl, MVT::i64); 11078 SDValue Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Reduce, Zero); 11079 11080 return Result; 11081 } 11082 11083 return SDValue(); 11084 } 11085 11086 static SDValue LowerSVEIntrinsicIndex(SDNode *N, SelectionDAG &DAG) { 11087 SDLoc DL(N); 11088 SDValue Op1 = N->getOperand(1); 11089 SDValue Op2 = N->getOperand(2); 11090 EVT ScalarTy = Op1.getValueType(); 11091 11092 if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) { 11093 Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1); 11094 Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2); 11095 } 11096 11097 return DAG.getNode(AArch64ISD::INDEX_VECTOR, DL, N->getValueType(0), 11098 Op1, Op2); 11099 } 11100 11101 static SDValue LowerSVEIntrinsicDUP(SDNode *N, SelectionDAG &DAG) { 11102 SDLoc dl(N); 11103 SDValue Scalar = N->getOperand(3); 11104 EVT ScalarTy = Scalar.getValueType(); 11105 11106 if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) 11107 Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar); 11108 11109 return DAG.getNode(AArch64ISD::DUP_PRED, dl, N->getValueType(0), 11110 N->getOperand(1), N->getOperand(2), Scalar); 11111 } 11112 11113 static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) { 11114 SDLoc dl(N); 11115 LLVMContext &Ctx = *DAG.getContext(); 11116 EVT VT = N->getValueType(0); 11117 11118 assert(VT.isScalableVector() && "Expected a scalable vector."); 11119 11120 // Current lowering only supports the SVE-ACLE types. 11121 if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock) 11122 return SDValue(); 11123 11124 unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8; 11125 unsigned ByteSize = VT.getSizeInBits().getKnownMinSize() / 8; 11126 EVT ByteVT = EVT::getVectorVT(Ctx, MVT::i8, { ByteSize, true }); 11127 11128 // Convert everything to the domain of EXT (i.e bytes). 11129 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1)); 11130 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2)); 11131 SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3), 11132 DAG.getConstant(ElemSize, dl, MVT::i32)); 11133 11134 SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2); 11135 return DAG.getNode(ISD::BITCAST, dl, VT, EXT); 11136 } 11137 11138 static SDValue tryConvertSVEWideCompare(SDNode *N, unsigned ReplacementIID, 11139 bool Invert, 11140 TargetLowering::DAGCombinerInfo &DCI, 11141 SelectionDAG &DAG) { 11142 if (DCI.isBeforeLegalize()) 11143 return SDValue(); 11144 11145 SDValue Comparator = N->getOperand(3); 11146 if (Comparator.getOpcode() == AArch64ISD::DUP || 11147 Comparator.getOpcode() == ISD::SPLAT_VECTOR) { 11148 unsigned IID = getIntrinsicID(N); 11149 EVT VT = N->getValueType(0); 11150 EVT CmpVT = N->getOperand(2).getValueType(); 11151 SDValue Pred = N->getOperand(1); 11152 SDValue Imm; 11153 SDLoc DL(N); 11154 11155 switch (IID) { 11156 default: 11157 llvm_unreachable("Called with wrong intrinsic!"); 11158 break; 11159 11160 // Signed comparisons 11161 case Intrinsic::aarch64_sve_cmpeq_wide: 11162 case Intrinsic::aarch64_sve_cmpne_wide: 11163 case Intrinsic::aarch64_sve_cmpge_wide: 11164 case Intrinsic::aarch64_sve_cmpgt_wide: 11165 case Intrinsic::aarch64_sve_cmplt_wide: 11166 case Intrinsic::aarch64_sve_cmple_wide: { 11167 if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) { 11168 int64_t ImmVal = CN->getSExtValue(); 11169 if (ImmVal >= -16 && ImmVal <= 15) 11170 Imm = DAG.getConstant(ImmVal, DL, MVT::i32); 11171 else 11172 return SDValue(); 11173 } 11174 break; 11175 } 11176 // Unsigned comparisons 11177 case Intrinsic::aarch64_sve_cmphs_wide: 11178 case Intrinsic::aarch64_sve_cmphi_wide: 11179 case Intrinsic::aarch64_sve_cmplo_wide: 11180 case Intrinsic::aarch64_sve_cmpls_wide: { 11181 if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) { 11182 uint64_t ImmVal = CN->getZExtValue(); 11183 if (ImmVal <= 127) 11184 Imm = DAG.getConstant(ImmVal, DL, MVT::i32); 11185 else 11186 return SDValue(); 11187 } 11188 break; 11189 } 11190 } 11191 11192 SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm); 11193 SDValue ID = DAG.getTargetConstant(ReplacementIID, DL, MVT::i64); 11194 SDValue Op0, Op1; 11195 if (Invert) { 11196 Op0 = Splat; 11197 Op1 = N->getOperand(2); 11198 } else { 11199 Op0 = N->getOperand(2); 11200 Op1 = Splat; 11201 } 11202 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 11203 ID, Pred, Op0, Op1); 11204 } 11205 11206 return SDValue(); 11207 } 11208 11209 static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op, 11210 AArch64CC::CondCode Cond) { 11211 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11212 11213 SDLoc DL(Op); 11214 assert(Op.getValueType().isScalableVector() && 11215 TLI.isTypeLegal(Op.getValueType()) && 11216 "Expected legal scalable vector type!"); 11217 11218 // Ensure target specific opcodes are using legal type. 11219 EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT); 11220 SDValue TVal = DAG.getConstant(1, DL, OutVT); 11221 SDValue FVal = DAG.getConstant(0, DL, OutVT); 11222 11223 // Set condition code (CC) flags. 11224 SDValue Test = DAG.getNode(AArch64ISD::PTEST, DL, MVT::Other, Pg, Op); 11225 11226 // Convert CC to integer based on requested condition. 11227 // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare. 11228 SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32); 11229 SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test); 11230 return DAG.getZExtOrTrunc(Res, DL, VT); 11231 } 11232 11233 static SDValue performIntrinsicCombine(SDNode *N, 11234 TargetLowering::DAGCombinerInfo &DCI, 11235 const AArch64Subtarget *Subtarget) { 11236 SelectionDAG &DAG = DCI.DAG; 11237 unsigned IID = getIntrinsicID(N); 11238 switch (IID) { 11239 default: 11240 break; 11241 case Intrinsic::aarch64_neon_vcvtfxs2fp: 11242 case Intrinsic::aarch64_neon_vcvtfxu2fp: 11243 return tryCombineFixedPointConvert(N, DCI, DAG); 11244 case Intrinsic::aarch64_neon_saddv: 11245 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG); 11246 case Intrinsic::aarch64_neon_uaddv: 11247 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG); 11248 case Intrinsic::aarch64_neon_sminv: 11249 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG); 11250 case Intrinsic::aarch64_neon_uminv: 11251 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG); 11252 case Intrinsic::aarch64_neon_smaxv: 11253 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG); 11254 case Intrinsic::aarch64_neon_umaxv: 11255 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG); 11256 case Intrinsic::aarch64_neon_fmax: 11257 return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0), 11258 N->getOperand(1), N->getOperand(2)); 11259 case Intrinsic::aarch64_neon_fmin: 11260 return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0), 11261 N->getOperand(1), N->getOperand(2)); 11262 case Intrinsic::aarch64_neon_fmaxnm: 11263 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0), 11264 N->getOperand(1), N->getOperand(2)); 11265 case Intrinsic::aarch64_neon_fminnm: 11266 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0), 11267 N->getOperand(1), N->getOperand(2)); 11268 case Intrinsic::aarch64_neon_smull: 11269 case Intrinsic::aarch64_neon_umull: 11270 case Intrinsic::aarch64_neon_pmull: 11271 case Intrinsic::aarch64_neon_sqdmull: 11272 return tryCombineLongOpWithDup(IID, N, DCI, DAG); 11273 case Intrinsic::aarch64_neon_sqshl: 11274 case Intrinsic::aarch64_neon_uqshl: 11275 case Intrinsic::aarch64_neon_sqshlu: 11276 case Intrinsic::aarch64_neon_srshl: 11277 case Intrinsic::aarch64_neon_urshl: 11278 case Intrinsic::aarch64_neon_sshl: 11279 case Intrinsic::aarch64_neon_ushl: 11280 return tryCombineShiftImm(IID, N, DAG); 11281 case Intrinsic::aarch64_crc32b: 11282 case Intrinsic::aarch64_crc32cb: 11283 return tryCombineCRC32(0xff, N, DAG); 11284 case Intrinsic::aarch64_crc32h: 11285 case Intrinsic::aarch64_crc32ch: 11286 return tryCombineCRC32(0xffff, N, DAG); 11287 case Intrinsic::aarch64_sve_smaxv: 11288 return LowerSVEIntReduction(N, AArch64ISD::SMAXV_PRED, DAG); 11289 case Intrinsic::aarch64_sve_umaxv: 11290 return LowerSVEIntReduction(N, AArch64ISD::UMAXV_PRED, DAG); 11291 case Intrinsic::aarch64_sve_sminv: 11292 return LowerSVEIntReduction(N, AArch64ISD::SMINV_PRED, DAG); 11293 case Intrinsic::aarch64_sve_uminv: 11294 return LowerSVEIntReduction(N, AArch64ISD::UMINV_PRED, DAG); 11295 case Intrinsic::aarch64_sve_orv: 11296 return LowerSVEIntReduction(N, AArch64ISD::ORV_PRED, DAG); 11297 case Intrinsic::aarch64_sve_eorv: 11298 return LowerSVEIntReduction(N, AArch64ISD::EORV_PRED, DAG); 11299 case Intrinsic::aarch64_sve_andv: 11300 return LowerSVEIntReduction(N, AArch64ISD::ANDV_PRED, DAG); 11301 case Intrinsic::aarch64_sve_index: 11302 return LowerSVEIntrinsicIndex(N, DAG); 11303 case Intrinsic::aarch64_sve_dup: 11304 return LowerSVEIntrinsicDUP(N, DAG); 11305 case Intrinsic::aarch64_sve_dup_x: 11306 return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), N->getValueType(0), 11307 N->getOperand(1)); 11308 case Intrinsic::aarch64_sve_ext: 11309 return LowerSVEIntrinsicEXT(N, DAG); 11310 case Intrinsic::aarch64_sve_sel: 11311 return DAG.getNode(ISD::VSELECT, SDLoc(N), N->getValueType(0), 11312 N->getOperand(1), N->getOperand(2), N->getOperand(3)); 11313 case Intrinsic::aarch64_sve_cmpeq_wide: 11314 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpeq, 11315 false, DCI, DAG); 11316 case Intrinsic::aarch64_sve_cmpne_wide: 11317 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpne, 11318 false, DCI, DAG); 11319 case Intrinsic::aarch64_sve_cmpge_wide: 11320 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpge, 11321 false, DCI, DAG); 11322 case Intrinsic::aarch64_sve_cmpgt_wide: 11323 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpgt, 11324 false, DCI, DAG); 11325 case Intrinsic::aarch64_sve_cmplt_wide: 11326 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpgt, 11327 true, DCI, DAG); 11328 case Intrinsic::aarch64_sve_cmple_wide: 11329 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmpge, 11330 true, DCI, DAG); 11331 case Intrinsic::aarch64_sve_cmphs_wide: 11332 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphs, 11333 false, DCI, DAG); 11334 case Intrinsic::aarch64_sve_cmphi_wide: 11335 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphi, 11336 false, DCI, DAG); 11337 case Intrinsic::aarch64_sve_cmplo_wide: 11338 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphi, true, 11339 DCI, DAG); 11340 case Intrinsic::aarch64_sve_cmpls_wide: 11341 return tryConvertSVEWideCompare(N, Intrinsic::aarch64_sve_cmphs, true, 11342 DCI, DAG); 11343 case Intrinsic::aarch64_sve_ptest_any: 11344 return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2), 11345 AArch64CC::ANY_ACTIVE); 11346 case Intrinsic::aarch64_sve_ptest_first: 11347 return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2), 11348 AArch64CC::FIRST_ACTIVE); 11349 case Intrinsic::aarch64_sve_ptest_last: 11350 return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2), 11351 AArch64CC::LAST_ACTIVE); 11352 } 11353 return SDValue(); 11354 } 11355 11356 static SDValue performExtendCombine(SDNode *N, 11357 TargetLowering::DAGCombinerInfo &DCI, 11358 SelectionDAG &DAG) { 11359 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then 11360 // we can convert that DUP into another extract_high (of a bigger DUP), which 11361 // helps the backend to decide that an sabdl2 would be useful, saving a real 11362 // extract_high operation. 11363 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND && 11364 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) { 11365 SDNode *ABDNode = N->getOperand(0).getNode(); 11366 unsigned IID = getIntrinsicID(ABDNode); 11367 if (IID == Intrinsic::aarch64_neon_sabd || 11368 IID == Intrinsic::aarch64_neon_uabd) { 11369 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG); 11370 if (!NewABD.getNode()) 11371 return SDValue(); 11372 11373 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), 11374 NewABD); 11375 } 11376 } 11377 11378 // This is effectively a custom type legalization for AArch64. 11379 // 11380 // Type legalization will split an extend of a small, legal, type to a larger 11381 // illegal type by first splitting the destination type, often creating 11382 // illegal source types, which then get legalized in isel-confusing ways, 11383 // leading to really terrible codegen. E.g., 11384 // %result = v8i32 sext v8i8 %value 11385 // becomes 11386 // %losrc = extract_subreg %value, ... 11387 // %hisrc = extract_subreg %value, ... 11388 // %lo = v4i32 sext v4i8 %losrc 11389 // %hi = v4i32 sext v4i8 %hisrc 11390 // Things go rapidly downhill from there. 11391 // 11392 // For AArch64, the [sz]ext vector instructions can only go up one element 11393 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32 11394 // take two instructions. 11395 // 11396 // This implies that the most efficient way to do the extend from v8i8 11397 // to two v4i32 values is to first extend the v8i8 to v8i16, then do 11398 // the normal splitting to happen for the v8i16->v8i32. 11399 11400 // This is pre-legalization to catch some cases where the default 11401 // type legalization will create ill-tempered code. 11402 if (!DCI.isBeforeLegalizeOps()) 11403 return SDValue(); 11404 11405 // We're only interested in cleaning things up for non-legal vector types 11406 // here. If both the source and destination are legal, things will just 11407 // work naturally without any fiddling. 11408 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11409 EVT ResVT = N->getValueType(0); 11410 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT)) 11411 return SDValue(); 11412 // If the vector type isn't a simple VT, it's beyond the scope of what 11413 // we're worried about here. Let legalization do its thing and hope for 11414 // the best. 11415 SDValue Src = N->getOperand(0); 11416 EVT SrcVT = Src->getValueType(0); 11417 if (!ResVT.isSimple() || !SrcVT.isSimple()) 11418 return SDValue(); 11419 11420 // If the source VT is a 64-bit vector, we can play games and get the 11421 // better results we want. 11422 if (SrcVT.getSizeInBits() != 64) 11423 return SDValue(); 11424 11425 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 11426 unsigned ElementCount = SrcVT.getVectorNumElements(); 11427 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount); 11428 SDLoc DL(N); 11429 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src); 11430 11431 // Now split the rest of the operation into two halves, each with a 64 11432 // bit source. 11433 EVT LoVT, HiVT; 11434 SDValue Lo, Hi; 11435 unsigned NumElements = ResVT.getVectorNumElements(); 11436 assert(!(NumElements & 1) && "Splitting vector, but not in half!"); 11437 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(), 11438 ResVT.getVectorElementType(), NumElements / 2); 11439 11440 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(), 11441 LoVT.getVectorNumElements()); 11442 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 11443 DAG.getConstant(0, DL, MVT::i64)); 11444 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 11445 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64)); 11446 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo); 11447 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi); 11448 11449 // Now combine the parts back together so we still have a single result 11450 // like the combiner expects. 11451 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi); 11452 } 11453 11454 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St, 11455 SDValue SplatVal, unsigned NumVecElts) { 11456 assert(!St.isTruncatingStore() && "cannot split truncating vector store"); 11457 unsigned OrigAlignment = St.getAlignment(); 11458 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8; 11459 11460 // Create scalar stores. This is at least as good as the code sequence for a 11461 // split unaligned store which is a dup.s, ext.b, and two stores. 11462 // Most of the time the three stores should be replaced by store pair 11463 // instructions (stp). 11464 SDLoc DL(&St); 11465 SDValue BasePtr = St.getBasePtr(); 11466 uint64_t BaseOffset = 0; 11467 11468 const MachinePointerInfo &PtrInfo = St.getPointerInfo(); 11469 SDValue NewST1 = 11470 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo, 11471 OrigAlignment, St.getMemOperand()->getFlags()); 11472 11473 // As this in ISel, we will not merge this add which may degrade results. 11474 if (BasePtr->getOpcode() == ISD::ADD && 11475 isa<ConstantSDNode>(BasePtr->getOperand(1))) { 11476 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue(); 11477 BasePtr = BasePtr->getOperand(0); 11478 } 11479 11480 unsigned Offset = EltOffset; 11481 while (--NumVecElts) { 11482 unsigned Alignment = MinAlign(OrigAlignment, Offset); 11483 SDValue OffsetPtr = 11484 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 11485 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64)); 11486 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr, 11487 PtrInfo.getWithOffset(Offset), Alignment, 11488 St.getMemOperand()->getFlags()); 11489 Offset += EltOffset; 11490 } 11491 return NewST1; 11492 } 11493 11494 // Returns an SVE type that ContentTy can be trivially sign or zero extended 11495 // into. 11496 static MVT getSVEContainerType(EVT ContentTy) { 11497 assert(ContentTy.isSimple() && "No SVE containers for extended types"); 11498 11499 switch (ContentTy.getSimpleVT().SimpleTy) { 11500 default: 11501 llvm_unreachable("No known SVE container for this MVT type"); 11502 case MVT::nxv2i8: 11503 case MVT::nxv2i16: 11504 case MVT::nxv2i32: 11505 case MVT::nxv2i64: 11506 case MVT::nxv2f32: 11507 case MVT::nxv2f64: 11508 return MVT::nxv2i64; 11509 case MVT::nxv4i8: 11510 case MVT::nxv4i16: 11511 case MVT::nxv4i32: 11512 case MVT::nxv4f32: 11513 return MVT::nxv4i32; 11514 case MVT::nxv8i8: 11515 case MVT::nxv8i16: 11516 case MVT::nxv8f16: 11517 return MVT::nxv8i16; 11518 case MVT::nxv16i8: 11519 return MVT::nxv16i8; 11520 } 11521 } 11522 11523 static SDValue performLD1Combine(SDNode *N, SelectionDAG &DAG) { 11524 SDLoc DL(N); 11525 EVT VT = N->getValueType(0); 11526 EVT PtrTy = N->getOperand(3).getValueType(); 11527 11528 EVT LoadVT = VT; 11529 if (VT.isFloatingPoint()) 11530 LoadVT = VT.changeTypeToInteger(); 11531 11532 auto *MINode = cast<MemIntrinsicSDNode>(N); 11533 SDValue PassThru = DAG.getConstant(0, DL, LoadVT); 11534 SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(), 11535 MINode->getOperand(3), DAG.getUNDEF(PtrTy), 11536 MINode->getOperand(2), PassThru, 11537 MINode->getMemoryVT(), MINode->getMemOperand(), 11538 ISD::UNINDEXED, ISD::NON_EXTLOAD, false); 11539 11540 if (VT.isFloatingPoint()) { 11541 SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) }; 11542 return DAG.getMergeValues(Ops, DL); 11543 } 11544 11545 return L; 11546 } 11547 11548 static SDValue performST1Combine(SDNode *N, SelectionDAG &DAG) { 11549 SDLoc DL(N); 11550 11551 SDValue Data = N->getOperand(2); 11552 EVT DataVT = Data.getValueType(); 11553 EVT PtrTy = N->getOperand(4).getValueType(); 11554 11555 if (DataVT.isFloatingPoint()) 11556 Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data); 11557 11558 auto *MINode = cast<MemIntrinsicSDNode>(N); 11559 return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4), 11560 DAG.getUNDEF(PtrTy), MINode->getOperand(3), 11561 MINode->getMemoryVT(), MINode->getMemOperand(), 11562 ISD::UNINDEXED, false, false); 11563 } 11564 11565 static SDValue performLDNF1Combine(SDNode *N, SelectionDAG &DAG, unsigned Opc) { 11566 SDLoc DL(N); 11567 EVT VT = N->getValueType(0); 11568 11569 if (VT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock) 11570 return SDValue(); 11571 11572 EVT ContainerVT = VT; 11573 if (ContainerVT.isInteger()) 11574 ContainerVT = getSVEContainerType(ContainerVT); 11575 11576 SDVTList VTs = DAG.getVTList(ContainerVT, MVT::Other); 11577 SDValue Ops[] = { N->getOperand(0), // Chain 11578 N->getOperand(2), // Pg 11579 N->getOperand(3), // Base 11580 DAG.getValueType(VT) }; 11581 11582 SDValue Load = DAG.getNode(Opc, DL, VTs, Ops); 11583 SDValue LoadChain = SDValue(Load.getNode(), 1); 11584 11585 if (ContainerVT.isInteger() && (VT != ContainerVT)) 11586 Load = DAG.getNode(ISD::TRUNCATE, DL, VT, Load.getValue(0)); 11587 11588 return DAG.getMergeValues({ Load, LoadChain }, DL); 11589 } 11590 11591 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The 11592 /// load store optimizer pass will merge them to store pair stores. This should 11593 /// be better than a movi to create the vector zero followed by a vector store 11594 /// if the zero constant is not re-used, since one instructions and one register 11595 /// live range will be removed. 11596 /// 11597 /// For example, the final generated code should be: 11598 /// 11599 /// stp xzr, xzr, [x0] 11600 /// 11601 /// instead of: 11602 /// 11603 /// movi v0.2d, #0 11604 /// str q0, [x0] 11605 /// 11606 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) { 11607 SDValue StVal = St.getValue(); 11608 EVT VT = StVal.getValueType(); 11609 11610 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or 11611 // 2, 3 or 4 i32 elements. 11612 int NumVecElts = VT.getVectorNumElements(); 11613 if (!(((NumVecElts == 2 || NumVecElts == 3) && 11614 VT.getVectorElementType().getSizeInBits() == 64) || 11615 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) && 11616 VT.getVectorElementType().getSizeInBits() == 32))) 11617 return SDValue(); 11618 11619 if (StVal.getOpcode() != ISD::BUILD_VECTOR) 11620 return SDValue(); 11621 11622 // If the zero constant has more than one use then the vector store could be 11623 // better since the constant mov will be amortized and stp q instructions 11624 // should be able to be formed. 11625 if (!StVal.hasOneUse()) 11626 return SDValue(); 11627 11628 // If the store is truncating then it's going down to i16 or smaller, which 11629 // means it can be implemented in a single store anyway. 11630 if (St.isTruncatingStore()) 11631 return SDValue(); 11632 11633 // If the immediate offset of the address operand is too large for the stp 11634 // instruction, then bail out. 11635 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) { 11636 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1); 11637 if (Offset < -512 || Offset > 504) 11638 return SDValue(); 11639 } 11640 11641 for (int I = 0; I < NumVecElts; ++I) { 11642 SDValue EltVal = StVal.getOperand(I); 11643 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal)) 11644 return SDValue(); 11645 } 11646 11647 // Use a CopyFromReg WZR/XZR here to prevent 11648 // DAGCombiner::MergeConsecutiveStores from undoing this transformation. 11649 SDLoc DL(&St); 11650 unsigned ZeroReg; 11651 EVT ZeroVT; 11652 if (VT.getVectorElementType().getSizeInBits() == 32) { 11653 ZeroReg = AArch64::WZR; 11654 ZeroVT = MVT::i32; 11655 } else { 11656 ZeroReg = AArch64::XZR; 11657 ZeroVT = MVT::i64; 11658 } 11659 SDValue SplatVal = 11660 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT); 11661 return splitStoreSplat(DAG, St, SplatVal, NumVecElts); 11662 } 11663 11664 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar 11665 /// value. The load store optimizer pass will merge them to store pair stores. 11666 /// This has better performance than a splat of the scalar followed by a split 11667 /// vector store. Even if the stores are not merged it is four stores vs a dup, 11668 /// followed by an ext.b and two stores. 11669 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) { 11670 SDValue StVal = St.getValue(); 11671 EVT VT = StVal.getValueType(); 11672 11673 // Don't replace floating point stores, they possibly won't be transformed to 11674 // stp because of the store pair suppress pass. 11675 if (VT.isFloatingPoint()) 11676 return SDValue(); 11677 11678 // We can express a splat as store pair(s) for 2 or 4 elements. 11679 unsigned NumVecElts = VT.getVectorNumElements(); 11680 if (NumVecElts != 4 && NumVecElts != 2) 11681 return SDValue(); 11682 11683 // If the store is truncating then it's going down to i16 or smaller, which 11684 // means it can be implemented in a single store anyway. 11685 if (St.isTruncatingStore()) 11686 return SDValue(); 11687 11688 // Check that this is a splat. 11689 // Make sure that each of the relevant vector element locations are inserted 11690 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32. 11691 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1); 11692 SDValue SplatVal; 11693 for (unsigned I = 0; I < NumVecElts; ++I) { 11694 // Check for insert vector elements. 11695 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT) 11696 return SDValue(); 11697 11698 // Check that same value is inserted at each vector element. 11699 if (I == 0) 11700 SplatVal = StVal.getOperand(1); 11701 else if (StVal.getOperand(1) != SplatVal) 11702 return SDValue(); 11703 11704 // Check insert element index. 11705 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2)); 11706 if (!CIndex) 11707 return SDValue(); 11708 uint64_t IndexVal = CIndex->getZExtValue(); 11709 if (IndexVal >= NumVecElts) 11710 return SDValue(); 11711 IndexNotInserted.reset(IndexVal); 11712 11713 StVal = StVal.getOperand(0); 11714 } 11715 // Check that all vector element locations were inserted to. 11716 if (IndexNotInserted.any()) 11717 return SDValue(); 11718 11719 return splitStoreSplat(DAG, St, SplatVal, NumVecElts); 11720 } 11721 11722 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 11723 SelectionDAG &DAG, 11724 const AArch64Subtarget *Subtarget) { 11725 11726 StoreSDNode *S = cast<StoreSDNode>(N); 11727 if (S->isVolatile() || S->isIndexed()) 11728 return SDValue(); 11729 11730 SDValue StVal = S->getValue(); 11731 EVT VT = StVal.getValueType(); 11732 if (!VT.isVector()) 11733 return SDValue(); 11734 11735 // If we get a splat of zeros, convert this vector store to a store of 11736 // scalars. They will be merged into store pairs of xzr thereby removing one 11737 // instruction and one register. 11738 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S)) 11739 return ReplacedZeroSplat; 11740 11741 // FIXME: The logic for deciding if an unaligned store should be split should 11742 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be 11743 // a call to that function here. 11744 11745 if (!Subtarget->isMisaligned128StoreSlow()) 11746 return SDValue(); 11747 11748 // Don't split at -Oz. 11749 if (DAG.getMachineFunction().getFunction().hasMinSize()) 11750 return SDValue(); 11751 11752 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting 11753 // those up regresses performance on micro-benchmarks and olden/bh. 11754 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64) 11755 return SDValue(); 11756 11757 // Split unaligned 16B stores. They are terrible for performance. 11758 // Don't split stores with alignment of 1 or 2. Code that uses clang vector 11759 // extensions can use this to mark that it does not want splitting to happen 11760 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of 11761 // eliminating alignment hazards is only 1 in 8 for alignment of 2. 11762 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 || 11763 S->getAlignment() <= 2) 11764 return SDValue(); 11765 11766 // If we get a splat of a scalar convert this vector store to a store of 11767 // scalars. They will be merged into store pairs thereby removing two 11768 // instructions. 11769 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S)) 11770 return ReplacedSplat; 11771 11772 SDLoc DL(S); 11773 11774 // Split VT into two. 11775 EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext()); 11776 unsigned NumElts = HalfVT.getVectorNumElements(); 11777 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 11778 DAG.getConstant(0, DL, MVT::i64)); 11779 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 11780 DAG.getConstant(NumElts, DL, MVT::i64)); 11781 SDValue BasePtr = S->getBasePtr(); 11782 SDValue NewST1 = 11783 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(), 11784 S->getAlignment(), S->getMemOperand()->getFlags()); 11785 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 11786 DAG.getConstant(8, DL, MVT::i64)); 11787 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr, 11788 S->getPointerInfo(), S->getAlignment(), 11789 S->getMemOperand()->getFlags()); 11790 } 11791 11792 /// Target-specific DAG combine function for post-increment LD1 (lane) and 11793 /// post-increment LD1R. 11794 static SDValue performPostLD1Combine(SDNode *N, 11795 TargetLowering::DAGCombinerInfo &DCI, 11796 bool IsLaneOp) { 11797 if (DCI.isBeforeLegalizeOps()) 11798 return SDValue(); 11799 11800 SelectionDAG &DAG = DCI.DAG; 11801 EVT VT = N->getValueType(0); 11802 11803 unsigned LoadIdx = IsLaneOp ? 1 : 0; 11804 SDNode *LD = N->getOperand(LoadIdx).getNode(); 11805 // If it is not LOAD, can not do such combine. 11806 if (LD->getOpcode() != ISD::LOAD) 11807 return SDValue(); 11808 11809 // The vector lane must be a constant in the LD1LANE opcode. 11810 SDValue Lane; 11811 if (IsLaneOp) { 11812 Lane = N->getOperand(2); 11813 auto *LaneC = dyn_cast<ConstantSDNode>(Lane); 11814 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements()) 11815 return SDValue(); 11816 } 11817 11818 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD); 11819 EVT MemVT = LoadSDN->getMemoryVT(); 11820 // Check if memory operand is the same type as the vector element. 11821 if (MemVT != VT.getVectorElementType()) 11822 return SDValue(); 11823 11824 // Check if there are other uses. If so, do not combine as it will introduce 11825 // an extra load. 11826 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE; 11827 ++UI) { 11828 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result. 11829 continue; 11830 if (*UI != N) 11831 return SDValue(); 11832 } 11833 11834 SDValue Addr = LD->getOperand(1); 11835 SDValue Vector = N->getOperand(0); 11836 // Search for a use of the address operand that is an increment. 11837 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE = 11838 Addr.getNode()->use_end(); UI != UE; ++UI) { 11839 SDNode *User = *UI; 11840 if (User->getOpcode() != ISD::ADD 11841 || UI.getUse().getResNo() != Addr.getResNo()) 11842 continue; 11843 11844 // If the increment is a constant, it must match the memory ref size. 11845 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 11846 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 11847 uint32_t IncVal = CInc->getZExtValue(); 11848 unsigned NumBytes = VT.getScalarSizeInBits() / 8; 11849 if (IncVal != NumBytes) 11850 continue; 11851 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 11852 } 11853 11854 // To avoid cycle construction make sure that neither the load nor the add 11855 // are predecessors to each other or the Vector. 11856 SmallPtrSet<const SDNode *, 32> Visited; 11857 SmallVector<const SDNode *, 16> Worklist; 11858 Visited.insert(Addr.getNode()); 11859 Worklist.push_back(User); 11860 Worklist.push_back(LD); 11861 Worklist.push_back(Vector.getNode()); 11862 if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) || 11863 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 11864 continue; 11865 11866 SmallVector<SDValue, 8> Ops; 11867 Ops.push_back(LD->getOperand(0)); // Chain 11868 if (IsLaneOp) { 11869 Ops.push_back(Vector); // The vector to be inserted 11870 Ops.push_back(Lane); // The lane to be inserted in the vector 11871 } 11872 Ops.push_back(Addr); 11873 Ops.push_back(Inc); 11874 11875 EVT Tys[3] = { VT, MVT::i64, MVT::Other }; 11876 SDVTList SDTys = DAG.getVTList(Tys); 11877 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost; 11878 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops, 11879 MemVT, 11880 LoadSDN->getMemOperand()); 11881 11882 // Update the uses. 11883 SDValue NewResults[] = { 11884 SDValue(LD, 0), // The result of load 11885 SDValue(UpdN.getNode(), 2) // Chain 11886 }; 11887 DCI.CombineTo(LD, NewResults); 11888 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result 11889 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register 11890 11891 break; 11892 } 11893 return SDValue(); 11894 } 11895 11896 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during 11897 /// address translation. 11898 static bool performTBISimplification(SDValue Addr, 11899 TargetLowering::DAGCombinerInfo &DCI, 11900 SelectionDAG &DAG) { 11901 APInt DemandedMask = APInt::getLowBitsSet(64, 56); 11902 KnownBits Known; 11903 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 11904 !DCI.isBeforeLegalizeOps()); 11905 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 11906 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) { 11907 DCI.CommitTargetLoweringOpt(TLO); 11908 return true; 11909 } 11910 return false; 11911 } 11912 11913 static SDValue performSTORECombine(SDNode *N, 11914 TargetLowering::DAGCombinerInfo &DCI, 11915 SelectionDAG &DAG, 11916 const AArch64Subtarget *Subtarget) { 11917 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget)) 11918 return Split; 11919 11920 if (Subtarget->supportsAddressTopByteIgnored() && 11921 performTBISimplification(N->getOperand(2), DCI, DAG)) 11922 return SDValue(N, 0); 11923 11924 return SDValue(); 11925 } 11926 11927 11928 /// Target-specific DAG combine function for NEON load/store intrinsics 11929 /// to merge base address updates. 11930 static SDValue performNEONPostLDSTCombine(SDNode *N, 11931 TargetLowering::DAGCombinerInfo &DCI, 11932 SelectionDAG &DAG) { 11933 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 11934 return SDValue(); 11935 11936 unsigned AddrOpIdx = N->getNumOperands() - 1; 11937 SDValue Addr = N->getOperand(AddrOpIdx); 11938 11939 // Search for a use of the address operand that is an increment. 11940 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 11941 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 11942 SDNode *User = *UI; 11943 if (User->getOpcode() != ISD::ADD || 11944 UI.getUse().getResNo() != Addr.getResNo()) 11945 continue; 11946 11947 // Check that the add is independent of the load/store. Otherwise, folding 11948 // it would create a cycle. 11949 SmallPtrSet<const SDNode *, 32> Visited; 11950 SmallVector<const SDNode *, 16> Worklist; 11951 Visited.insert(Addr.getNode()); 11952 Worklist.push_back(N); 11953 Worklist.push_back(User); 11954 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 11955 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 11956 continue; 11957 11958 // Find the new opcode for the updating load/store. 11959 bool IsStore = false; 11960 bool IsLaneOp = false; 11961 bool IsDupOp = false; 11962 unsigned NewOpc = 0; 11963 unsigned NumVecs = 0; 11964 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 11965 switch (IntNo) { 11966 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 11967 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post; 11968 NumVecs = 2; break; 11969 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post; 11970 NumVecs = 3; break; 11971 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post; 11972 NumVecs = 4; break; 11973 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post; 11974 NumVecs = 2; IsStore = true; break; 11975 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post; 11976 NumVecs = 3; IsStore = true; break; 11977 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post; 11978 NumVecs = 4; IsStore = true; break; 11979 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post; 11980 NumVecs = 2; break; 11981 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post; 11982 NumVecs = 3; break; 11983 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post; 11984 NumVecs = 4; break; 11985 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post; 11986 NumVecs = 2; IsStore = true; break; 11987 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post; 11988 NumVecs = 3; IsStore = true; break; 11989 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post; 11990 NumVecs = 4; IsStore = true; break; 11991 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost; 11992 NumVecs = 2; IsDupOp = true; break; 11993 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost; 11994 NumVecs = 3; IsDupOp = true; break; 11995 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost; 11996 NumVecs = 4; IsDupOp = true; break; 11997 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost; 11998 NumVecs = 2; IsLaneOp = true; break; 11999 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost; 12000 NumVecs = 3; IsLaneOp = true; break; 12001 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost; 12002 NumVecs = 4; IsLaneOp = true; break; 12003 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost; 12004 NumVecs = 2; IsStore = true; IsLaneOp = true; break; 12005 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost; 12006 NumVecs = 3; IsStore = true; IsLaneOp = true; break; 12007 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost; 12008 NumVecs = 4; IsStore = true; IsLaneOp = true; break; 12009 } 12010 12011 EVT VecTy; 12012 if (IsStore) 12013 VecTy = N->getOperand(2).getValueType(); 12014 else 12015 VecTy = N->getValueType(0); 12016 12017 // If the increment is a constant, it must match the memory ref size. 12018 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 12019 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 12020 uint32_t IncVal = CInc->getZExtValue(); 12021 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 12022 if (IsLaneOp || IsDupOp) 12023 NumBytes /= VecTy.getVectorNumElements(); 12024 if (IncVal != NumBytes) 12025 continue; 12026 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 12027 } 12028 SmallVector<SDValue, 8> Ops; 12029 Ops.push_back(N->getOperand(0)); // Incoming chain 12030 // Load lane and store have vector list as input. 12031 if (IsLaneOp || IsStore) 12032 for (unsigned i = 2; i < AddrOpIdx; ++i) 12033 Ops.push_back(N->getOperand(i)); 12034 Ops.push_back(Addr); // Base register 12035 Ops.push_back(Inc); 12036 12037 // Return Types. 12038 EVT Tys[6]; 12039 unsigned NumResultVecs = (IsStore ? 0 : NumVecs); 12040 unsigned n; 12041 for (n = 0; n < NumResultVecs; ++n) 12042 Tys[n] = VecTy; 12043 Tys[n++] = MVT::i64; // Type of write back register 12044 Tys[n] = MVT::Other; // Type of the chain 12045 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2)); 12046 12047 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N); 12048 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops, 12049 MemInt->getMemoryVT(), 12050 MemInt->getMemOperand()); 12051 12052 // Update the uses. 12053 std::vector<SDValue> NewResults; 12054 for (unsigned i = 0; i < NumResultVecs; ++i) { 12055 NewResults.push_back(SDValue(UpdN.getNode(), i)); 12056 } 12057 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); 12058 DCI.CombineTo(N, NewResults); 12059 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 12060 12061 break; 12062 } 12063 return SDValue(); 12064 } 12065 12066 // Checks to see if the value is the prescribed width and returns information 12067 // about its extension mode. 12068 static 12069 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) { 12070 ExtType = ISD::NON_EXTLOAD; 12071 switch(V.getNode()->getOpcode()) { 12072 default: 12073 return false; 12074 case ISD::LOAD: { 12075 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode()); 12076 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8) 12077 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) { 12078 ExtType = LoadNode->getExtensionType(); 12079 return true; 12080 } 12081 return false; 12082 } 12083 case ISD::AssertSext: { 12084 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 12085 if ((TypeNode->getVT() == MVT::i8 && width == 8) 12086 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 12087 ExtType = ISD::SEXTLOAD; 12088 return true; 12089 } 12090 return false; 12091 } 12092 case ISD::AssertZext: { 12093 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 12094 if ((TypeNode->getVT() == MVT::i8 && width == 8) 12095 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 12096 ExtType = ISD::ZEXTLOAD; 12097 return true; 12098 } 12099 return false; 12100 } 12101 case ISD::Constant: 12102 case ISD::TargetConstant: { 12103 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) < 12104 1LL << (width - 1); 12105 } 12106 } 12107 12108 return true; 12109 } 12110 12111 // This function does a whole lot of voodoo to determine if the tests are 12112 // equivalent without and with a mask. Essentially what happens is that given a 12113 // DAG resembling: 12114 // 12115 // +-------------+ +-------------+ +-------------+ +-------------+ 12116 // | Input | | AddConstant | | CompConstant| | CC | 12117 // +-------------+ +-------------+ +-------------+ +-------------+ 12118 // | | | | 12119 // V V | +----------+ 12120 // +-------------+ +----+ | | 12121 // | ADD | |0xff| | | 12122 // +-------------+ +----+ | | 12123 // | | | | 12124 // V V | | 12125 // +-------------+ | | 12126 // | AND | | | 12127 // +-------------+ | | 12128 // | | | 12129 // +-----+ | | 12130 // | | | 12131 // V V V 12132 // +-------------+ 12133 // | CMP | 12134 // +-------------+ 12135 // 12136 // The AND node may be safely removed for some combinations of inputs. In 12137 // particular we need to take into account the extension type of the Input, 12138 // the exact values of AddConstant, CompConstant, and CC, along with the nominal 12139 // width of the input (this can work for any width inputs, the above graph is 12140 // specific to 8 bits. 12141 // 12142 // The specific equations were worked out by generating output tables for each 12143 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The 12144 // problem was simplified by working with 4 bit inputs, which means we only 12145 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero 12146 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8 12147 // patterns present in both extensions (0,7). For every distinct set of 12148 // AddConstant and CompConstants bit patterns we can consider the masked and 12149 // unmasked versions to be equivalent if the result of this function is true for 12150 // all 16 distinct bit patterns of for the current extension type of Input (w0). 12151 // 12152 // sub w8, w0, w1 12153 // and w10, w8, #0x0f 12154 // cmp w8, w2 12155 // cset w9, AArch64CC 12156 // cmp w10, w2 12157 // cset w11, AArch64CC 12158 // cmp w9, w11 12159 // cset w0, eq 12160 // ret 12161 // 12162 // Since the above function shows when the outputs are equivalent it defines 12163 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and 12164 // would be expensive to run during compiles. The equations below were written 12165 // in a test harness that confirmed they gave equivalent outputs to the above 12166 // for all inputs function, so they can be used determine if the removal is 12167 // legal instead. 12168 // 12169 // isEquivalentMaskless() is the code for testing if the AND can be removed 12170 // factored out of the DAG recognition as the DAG can take several forms. 12171 12172 static bool isEquivalentMaskless(unsigned CC, unsigned width, 12173 ISD::LoadExtType ExtType, int AddConstant, 12174 int CompConstant) { 12175 // By being careful about our equations and only writing the in term 12176 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can 12177 // make them generally applicable to all bit widths. 12178 int MaxUInt = (1 << width); 12179 12180 // For the purposes of these comparisons sign extending the type is 12181 // equivalent to zero extending the add and displacing it by half the integer 12182 // width. Provided we are careful and make sure our equations are valid over 12183 // the whole range we can just adjust the input and avoid writing equations 12184 // for sign extended inputs. 12185 if (ExtType == ISD::SEXTLOAD) 12186 AddConstant -= (1 << (width-1)); 12187 12188 switch(CC) { 12189 case AArch64CC::LE: 12190 case AArch64CC::GT: 12191 if ((AddConstant == 0) || 12192 (CompConstant == MaxUInt - 1 && AddConstant < 0) || 12193 (AddConstant >= 0 && CompConstant < 0) || 12194 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant)) 12195 return true; 12196 break; 12197 case AArch64CC::LT: 12198 case AArch64CC::GE: 12199 if ((AddConstant == 0) || 12200 (AddConstant >= 0 && CompConstant <= 0) || 12201 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant)) 12202 return true; 12203 break; 12204 case AArch64CC::HI: 12205 case AArch64CC::LS: 12206 if ((AddConstant >= 0 && CompConstant < 0) || 12207 (AddConstant <= 0 && CompConstant >= -1 && 12208 CompConstant < AddConstant + MaxUInt)) 12209 return true; 12210 break; 12211 case AArch64CC::PL: 12212 case AArch64CC::MI: 12213 if ((AddConstant == 0) || 12214 (AddConstant > 0 && CompConstant <= 0) || 12215 (AddConstant < 0 && CompConstant <= AddConstant)) 12216 return true; 12217 break; 12218 case AArch64CC::LO: 12219 case AArch64CC::HS: 12220 if ((AddConstant >= 0 && CompConstant <= 0) || 12221 (AddConstant <= 0 && CompConstant >= 0 && 12222 CompConstant <= AddConstant + MaxUInt)) 12223 return true; 12224 break; 12225 case AArch64CC::EQ: 12226 case AArch64CC::NE: 12227 if ((AddConstant > 0 && CompConstant < 0) || 12228 (AddConstant < 0 && CompConstant >= 0 && 12229 CompConstant < AddConstant + MaxUInt) || 12230 (AddConstant >= 0 && CompConstant >= 0 && 12231 CompConstant >= AddConstant) || 12232 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant)) 12233 return true; 12234 break; 12235 case AArch64CC::VS: 12236 case AArch64CC::VC: 12237 case AArch64CC::AL: 12238 case AArch64CC::NV: 12239 return true; 12240 case AArch64CC::Invalid: 12241 break; 12242 } 12243 12244 return false; 12245 } 12246 12247 static 12248 SDValue performCONDCombine(SDNode *N, 12249 TargetLowering::DAGCombinerInfo &DCI, 12250 SelectionDAG &DAG, unsigned CCIndex, 12251 unsigned CmpIndex) { 12252 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue(); 12253 SDNode *SubsNode = N->getOperand(CmpIndex).getNode(); 12254 unsigned CondOpcode = SubsNode->getOpcode(); 12255 12256 if (CondOpcode != AArch64ISD::SUBS) 12257 return SDValue(); 12258 12259 // There is a SUBS feeding this condition. Is it fed by a mask we can 12260 // use? 12261 12262 SDNode *AndNode = SubsNode->getOperand(0).getNode(); 12263 unsigned MaskBits = 0; 12264 12265 if (AndNode->getOpcode() != ISD::AND) 12266 return SDValue(); 12267 12268 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) { 12269 uint32_t CNV = CN->getZExtValue(); 12270 if (CNV == 255) 12271 MaskBits = 8; 12272 else if (CNV == 65535) 12273 MaskBits = 16; 12274 } 12275 12276 if (!MaskBits) 12277 return SDValue(); 12278 12279 SDValue AddValue = AndNode->getOperand(0); 12280 12281 if (AddValue.getOpcode() != ISD::ADD) 12282 return SDValue(); 12283 12284 // The basic dag structure is correct, grab the inputs and validate them. 12285 12286 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0); 12287 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1); 12288 SDValue SubsInputValue = SubsNode->getOperand(1); 12289 12290 // The mask is present and the provenance of all the values is a smaller type, 12291 // lets see if the mask is superfluous. 12292 12293 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) || 12294 !isa<ConstantSDNode>(SubsInputValue.getNode())) 12295 return SDValue(); 12296 12297 ISD::LoadExtType ExtType; 12298 12299 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) || 12300 !checkValueWidth(AddInputValue2, MaskBits, ExtType) || 12301 !checkValueWidth(AddInputValue1, MaskBits, ExtType) ) 12302 return SDValue(); 12303 12304 if(!isEquivalentMaskless(CC, MaskBits, ExtType, 12305 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(), 12306 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue())) 12307 return SDValue(); 12308 12309 // The AND is not necessary, remove it. 12310 12311 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0), 12312 SubsNode->getValueType(1)); 12313 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) }; 12314 12315 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops); 12316 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode()); 12317 12318 return SDValue(N, 0); 12319 } 12320 12321 // Optimize compare with zero and branch. 12322 static SDValue performBRCONDCombine(SDNode *N, 12323 TargetLowering::DAGCombinerInfo &DCI, 12324 SelectionDAG &DAG) { 12325 MachineFunction &MF = DAG.getMachineFunction(); 12326 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions 12327 // will not be produced, as they are conditional branch instructions that do 12328 // not set flags. 12329 if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening)) 12330 return SDValue(); 12331 12332 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3)) 12333 N = NV.getNode(); 12334 SDValue Chain = N->getOperand(0); 12335 SDValue Dest = N->getOperand(1); 12336 SDValue CCVal = N->getOperand(2); 12337 SDValue Cmp = N->getOperand(3); 12338 12339 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!"); 12340 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue(); 12341 if (CC != AArch64CC::EQ && CC != AArch64CC::NE) 12342 return SDValue(); 12343 12344 unsigned CmpOpc = Cmp.getOpcode(); 12345 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS) 12346 return SDValue(); 12347 12348 // Only attempt folding if there is only one use of the flag and no use of the 12349 // value. 12350 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1)) 12351 return SDValue(); 12352 12353 SDValue LHS = Cmp.getOperand(0); 12354 SDValue RHS = Cmp.getOperand(1); 12355 12356 assert(LHS.getValueType() == RHS.getValueType() && 12357 "Expected the value type to be the same for both operands!"); 12358 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 12359 return SDValue(); 12360 12361 if (isNullConstant(LHS)) 12362 std::swap(LHS, RHS); 12363 12364 if (!isNullConstant(RHS)) 12365 return SDValue(); 12366 12367 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA || 12368 LHS.getOpcode() == ISD::SRL) 12369 return SDValue(); 12370 12371 // Fold the compare into the branch instruction. 12372 SDValue BR; 12373 if (CC == AArch64CC::EQ) 12374 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 12375 else 12376 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 12377 12378 // Do not add new nodes to DAG combiner worklist. 12379 DCI.CombineTo(N, BR, false); 12380 12381 return SDValue(); 12382 } 12383 12384 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test 12385 // as well as whether the test should be inverted. This code is required to 12386 // catch these cases (as opposed to standard dag combines) because 12387 // AArch64ISD::TBZ is matched during legalization. 12388 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert, 12389 SelectionDAG &DAG) { 12390 12391 if (!Op->hasOneUse()) 12392 return Op; 12393 12394 // We don't handle undef/constant-fold cases below, as they should have 12395 // already been taken care of (e.g. and of 0, test of undefined shifted bits, 12396 // etc.) 12397 12398 // (tbz (trunc x), b) -> (tbz x, b) 12399 // This case is just here to enable more of the below cases to be caught. 12400 if (Op->getOpcode() == ISD::TRUNCATE && 12401 Bit < Op->getValueType(0).getSizeInBits()) { 12402 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 12403 } 12404 12405 // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits. 12406 if (Op->getOpcode() == ISD::ANY_EXTEND && 12407 Bit < Op->getOperand(0).getValueSizeInBits()) { 12408 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 12409 } 12410 12411 if (Op->getNumOperands() != 2) 12412 return Op; 12413 12414 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 12415 if (!C) 12416 return Op; 12417 12418 switch (Op->getOpcode()) { 12419 default: 12420 return Op; 12421 12422 // (tbz (and x, m), b) -> (tbz x, b) 12423 case ISD::AND: 12424 if ((C->getZExtValue() >> Bit) & 1) 12425 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 12426 return Op; 12427 12428 // (tbz (shl x, c), b) -> (tbz x, b-c) 12429 case ISD::SHL: 12430 if (C->getZExtValue() <= Bit && 12431 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 12432 Bit = Bit - C->getZExtValue(); 12433 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 12434 } 12435 return Op; 12436 12437 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x 12438 case ISD::SRA: 12439 Bit = Bit + C->getZExtValue(); 12440 if (Bit >= Op->getValueType(0).getSizeInBits()) 12441 Bit = Op->getValueType(0).getSizeInBits() - 1; 12442 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 12443 12444 // (tbz (srl x, c), b) -> (tbz x, b+c) 12445 case ISD::SRL: 12446 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 12447 Bit = Bit + C->getZExtValue(); 12448 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 12449 } 12450 return Op; 12451 12452 // (tbz (xor x, -1), b) -> (tbnz x, b) 12453 case ISD::XOR: 12454 if ((C->getZExtValue() >> Bit) & 1) 12455 Invert = !Invert; 12456 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 12457 } 12458 } 12459 12460 // Optimize test single bit zero/non-zero and branch. 12461 static SDValue performTBZCombine(SDNode *N, 12462 TargetLowering::DAGCombinerInfo &DCI, 12463 SelectionDAG &DAG) { 12464 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 12465 bool Invert = false; 12466 SDValue TestSrc = N->getOperand(1); 12467 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG); 12468 12469 if (TestSrc == NewTestSrc) 12470 return SDValue(); 12471 12472 unsigned NewOpc = N->getOpcode(); 12473 if (Invert) { 12474 if (NewOpc == AArch64ISD::TBZ) 12475 NewOpc = AArch64ISD::TBNZ; 12476 else { 12477 assert(NewOpc == AArch64ISD::TBNZ); 12478 NewOpc = AArch64ISD::TBZ; 12479 } 12480 } 12481 12482 SDLoc DL(N); 12483 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc, 12484 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3)); 12485 } 12486 12487 // vselect (v1i1 setcc) -> 12488 // vselect (v1iXX setcc) (XX is the size of the compared operand type) 12489 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as 12490 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine 12491 // such VSELECT. 12492 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) { 12493 SDValue N0 = N->getOperand(0); 12494 EVT CCVT = N0.getValueType(); 12495 12496 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 || 12497 CCVT.getVectorElementType() != MVT::i1) 12498 return SDValue(); 12499 12500 EVT ResVT = N->getValueType(0); 12501 EVT CmpVT = N0.getOperand(0).getValueType(); 12502 // Only combine when the result type is of the same size as the compared 12503 // operands. 12504 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits()) 12505 return SDValue(); 12506 12507 SDValue IfTrue = N->getOperand(1); 12508 SDValue IfFalse = N->getOperand(2); 12509 SDValue SetCC = 12510 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(), 12511 N0.getOperand(0), N0.getOperand(1), 12512 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 12513 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC, 12514 IfTrue, IfFalse); 12515 } 12516 12517 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with 12518 /// the compare-mask instructions rather than going via NZCV, even if LHS and 12519 /// RHS are really scalar. This replaces any scalar setcc in the above pattern 12520 /// with a vector one followed by a DUP shuffle on the result. 12521 static SDValue performSelectCombine(SDNode *N, 12522 TargetLowering::DAGCombinerInfo &DCI) { 12523 SelectionDAG &DAG = DCI.DAG; 12524 SDValue N0 = N->getOperand(0); 12525 EVT ResVT = N->getValueType(0); 12526 12527 if (N0.getOpcode() != ISD::SETCC) 12528 return SDValue(); 12529 12530 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered 12531 // scalar SetCCResultType. We also don't expect vectors, because we assume 12532 // that selects fed by vector SETCCs are canonicalized to VSELECT. 12533 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) && 12534 "Scalar-SETCC feeding SELECT has unexpected result type!"); 12535 12536 // If NumMaskElts == 0, the comparison is larger than select result. The 12537 // largest real NEON comparison is 64-bits per lane, which means the result is 12538 // at most 32-bits and an illegal vector. Just bail out for now. 12539 EVT SrcVT = N0.getOperand(0).getValueType(); 12540 12541 // Don't try to do this optimization when the setcc itself has i1 operands. 12542 // There are no legal vectors of i1, so this would be pointless. 12543 if (SrcVT == MVT::i1) 12544 return SDValue(); 12545 12546 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits(); 12547 if (!ResVT.isVector() || NumMaskElts == 0) 12548 return SDValue(); 12549 12550 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts); 12551 EVT CCVT = SrcVT.changeVectorElementTypeToInteger(); 12552 12553 // Also bail out if the vector CCVT isn't the same size as ResVT. 12554 // This can happen if the SETCC operand size doesn't divide the ResVT size 12555 // (e.g., f64 vs v3f32). 12556 if (CCVT.getSizeInBits() != ResVT.getSizeInBits()) 12557 return SDValue(); 12558 12559 // Make sure we didn't create illegal types, if we're not supposed to. 12560 assert(DCI.isBeforeLegalize() || 12561 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT)); 12562 12563 // First perform a vector comparison, where lane 0 is the one we're interested 12564 // in. 12565 SDLoc DL(N0); 12566 SDValue LHS = 12567 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0)); 12568 SDValue RHS = 12569 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1)); 12570 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2)); 12571 12572 // Now duplicate the comparison mask we want across all other lanes. 12573 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0); 12574 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask); 12575 Mask = DAG.getNode(ISD::BITCAST, DL, 12576 ResVT.changeVectorElementTypeToInteger(), Mask); 12577 12578 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2)); 12579 } 12580 12581 /// Get rid of unnecessary NVCASTs (that don't change the type). 12582 static SDValue performNVCASTCombine(SDNode *N) { 12583 if (N->getValueType(0) == N->getOperand(0).getValueType()) 12584 return N->getOperand(0); 12585 12586 return SDValue(); 12587 } 12588 12589 // If all users of the globaladdr are of the form (globaladdr + constant), find 12590 // the smallest constant, fold it into the globaladdr's offset and rewrite the 12591 // globaladdr as (globaladdr + constant) - constant. 12592 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG, 12593 const AArch64Subtarget *Subtarget, 12594 const TargetMachine &TM) { 12595 auto *GN = cast<GlobalAddressSDNode>(N); 12596 if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) != 12597 AArch64II::MO_NO_FLAG) 12598 return SDValue(); 12599 12600 uint64_t MinOffset = -1ull; 12601 for (SDNode *N : GN->uses()) { 12602 if (N->getOpcode() != ISD::ADD) 12603 return SDValue(); 12604 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0)); 12605 if (!C) 12606 C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 12607 if (!C) 12608 return SDValue(); 12609 MinOffset = std::min(MinOffset, C->getZExtValue()); 12610 } 12611 uint64_t Offset = MinOffset + GN->getOffset(); 12612 12613 // Require that the new offset is larger than the existing one. Otherwise, we 12614 // can end up oscillating between two possible DAGs, for example, 12615 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1). 12616 if (Offset <= uint64_t(GN->getOffset())) 12617 return SDValue(); 12618 12619 // Check whether folding this offset is legal. It must not go out of bounds of 12620 // the referenced object to avoid violating the code model, and must be 12621 // smaller than 2^21 because this is the largest offset expressible in all 12622 // object formats. 12623 // 12624 // This check also prevents us from folding negative offsets, which will end 12625 // up being treated in the same way as large positive ones. They could also 12626 // cause code model violations, and aren't really common enough to matter. 12627 if (Offset >= (1 << 21)) 12628 return SDValue(); 12629 12630 const GlobalValue *GV = GN->getGlobal(); 12631 Type *T = GV->getValueType(); 12632 if (!T->isSized() || 12633 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T)) 12634 return SDValue(); 12635 12636 SDLoc DL(GN); 12637 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset); 12638 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result, 12639 DAG.getConstant(MinOffset, DL, MVT::i64)); 12640 } 12641 12642 // Turns the vector of indices into a vector of byte offstes by scaling Offset 12643 // by (BitWidth / 8). 12644 static SDValue getScaledOffsetForBitWidth(SelectionDAG &DAG, SDValue Offset, 12645 SDLoc DL, unsigned BitWidth) { 12646 assert(Offset.getValueType().isScalableVector() && 12647 "This method is only for scalable vectors of offsets"); 12648 12649 SDValue Shift = DAG.getConstant(Log2_32(BitWidth / 8), DL, MVT::i64); 12650 SDValue SplatShift = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Shift); 12651 12652 return DAG.getNode(ISD::SHL, DL, MVT::nxv2i64, Offset, SplatShift); 12653 } 12654 12655 /// Check if the value of \p OffsetInBytes can be used as an immediate for 12656 /// the gather load/prefetch and scatter store instructions with vector base and 12657 /// immediate offset addressing mode: 12658 /// 12659 /// [<Zn>.[S|D]{, #<imm>}] 12660 /// 12661 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31. 12662 12663 inline static bool isValidImmForSVEVecImmAddrMode(unsigned OffsetInBytes, 12664 unsigned ScalarSizeInBytes) { 12665 // The immediate is not a multiple of the scalar size. 12666 if (OffsetInBytes % ScalarSizeInBytes) 12667 return false; 12668 12669 // The immediate is out of range. 12670 if (OffsetInBytes / ScalarSizeInBytes > 31) 12671 return false; 12672 12673 return true; 12674 } 12675 12676 /// Check if the value of \p Offset represents a valid immediate for the SVE 12677 /// gather load/prefetch and scatter store instructiona with vector base and 12678 /// immediate offset addressing mode: 12679 /// 12680 /// [<Zn>.[S|D]{, #<imm>}] 12681 /// 12682 /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31. 12683 static bool isValidImmForSVEVecImmAddrMode(SDValue Offset, 12684 unsigned ScalarSizeInBytes) { 12685 ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode()); 12686 return OffsetConst && isValidImmForSVEVecImmAddrMode( 12687 OffsetConst->getZExtValue(), ScalarSizeInBytes); 12688 } 12689 12690 static SDValue performScatterStoreCombine(SDNode *N, SelectionDAG &DAG, 12691 unsigned Opcode, 12692 bool OnlyPackedOffsets = true) { 12693 const SDValue Src = N->getOperand(2); 12694 const EVT SrcVT = Src->getValueType(0); 12695 assert(SrcVT.isScalableVector() && 12696 "Scatter stores are only possible for SVE vectors"); 12697 12698 SDLoc DL(N); 12699 MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT(); 12700 12701 // Make sure that source data will fit into an SVE register 12702 if (SrcVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock) 12703 return SDValue(); 12704 12705 // For FPs, ACLE only supports _packed_ single and double precision types. 12706 if (SrcElVT.isFloatingPoint()) 12707 if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64)) 12708 return SDValue(); 12709 12710 // Depending on the addressing mode, this is either a pointer or a vector of 12711 // pointers (that fits into one register) 12712 SDValue Base = N->getOperand(4); 12713 // Depending on the addressing mode, this is either a single offset or a 12714 // vector of offsets (that fits into one register) 12715 SDValue Offset = N->getOperand(5); 12716 12717 // For "scalar + vector of indices", just scale the indices. This only 12718 // applies to non-temporal scatters because there's no instruction that takes 12719 // indicies. 12720 if (Opcode == AArch64ISD::SSTNT1_INDEX) { 12721 Offset = 12722 getScaledOffsetForBitWidth(DAG, Offset, DL, SrcElVT.getSizeInBits()); 12723 Opcode = AArch64ISD::SSTNT1; 12724 } 12725 12726 // In the case of non-temporal gather loads there's only one SVE instruction 12727 // per data-size: "scalar + vector", i.e. 12728 // * stnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0] 12729 // Since we do have intrinsics that allow the arguments to be in a different 12730 // order, we may need to swap them to match the spec. 12731 if (Opcode == AArch64ISD::SSTNT1 && Offset.getValueType().isVector()) 12732 std::swap(Base, Offset); 12733 12734 // SST1_IMM requires that the offset is an immediate that is: 12735 // * a multiple of #SizeInBytes, 12736 // * in the range [0, 31 x #SizeInBytes], 12737 // where #SizeInBytes is the size in bytes of the stored items. For 12738 // immediates outside that range and non-immediate scalar offsets use SST1 or 12739 // SST1_UXTW instead. 12740 if (Opcode == AArch64ISD::SST1_IMM) { 12741 if (!isValidImmForSVEVecImmAddrMode(Offset, 12742 SrcVT.getScalarSizeInBits() / 8)) { 12743 if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy) 12744 Opcode = AArch64ISD::SST1_UXTW; 12745 else 12746 Opcode = AArch64ISD::SST1; 12747 12748 std::swap(Base, Offset); 12749 } 12750 } 12751 12752 auto &TLI = DAG.getTargetLoweringInfo(); 12753 if (!TLI.isTypeLegal(Base.getValueType())) 12754 return SDValue(); 12755 12756 // Some scatter store variants allow unpacked offsets, but only as nxv2i32 12757 // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to 12758 // nxv2i64. Legalize accordingly. 12759 if (!OnlyPackedOffsets && 12760 Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32) 12761 Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0); 12762 12763 if (!TLI.isTypeLegal(Offset.getValueType())) 12764 return SDValue(); 12765 12766 // Source value type that is representable in hardware 12767 EVT HwSrcVt = getSVEContainerType(SrcVT); 12768 12769 // Keep the original type of the input data to store - this is needed to be 12770 // able to select the correct instruction, e.g. ST1B, ST1H, ST1W and ST1D. For 12771 // FP values we want the integer equivalent, so just use HwSrcVt. 12772 SDValue InputVT = DAG.getValueType(SrcVT); 12773 if (SrcVT.isFloatingPoint()) 12774 InputVT = DAG.getValueType(HwSrcVt); 12775 12776 SDVTList VTs = DAG.getVTList(MVT::Other); 12777 SDValue SrcNew; 12778 12779 if (Src.getValueType().isFloatingPoint()) 12780 SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src); 12781 else 12782 SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src); 12783 12784 SDValue Ops[] = {N->getOperand(0), // Chain 12785 SrcNew, 12786 N->getOperand(3), // Pg 12787 Base, 12788 Offset, 12789 InputVT}; 12790 12791 return DAG.getNode(Opcode, DL, VTs, Ops); 12792 } 12793 12794 static SDValue performGatherLoadCombine(SDNode *N, SelectionDAG &DAG, 12795 unsigned Opcode, 12796 bool OnlyPackedOffsets = true) { 12797 const EVT RetVT = N->getValueType(0); 12798 assert(RetVT.isScalableVector() && 12799 "Gather loads are only possible for SVE vectors"); 12800 12801 SDLoc DL(N); 12802 12803 // Make sure that the loaded data will fit into an SVE register 12804 if (RetVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock) 12805 return SDValue(); 12806 12807 // Depending on the addressing mode, this is either a pointer or a vector of 12808 // pointers (that fits into one register) 12809 SDValue Base = N->getOperand(3); 12810 // Depending on the addressing mode, this is either a single offset or a 12811 // vector of offsets (that fits into one register) 12812 SDValue Offset = N->getOperand(4); 12813 12814 // For "scalar + vector of indices", just scale the indices. This only 12815 // applies to non-temporal gathers because there's no instruction that takes 12816 // indicies. 12817 if (Opcode == AArch64ISD::GLDNT1_INDEX) { 12818 Offset = getScaledOffsetForBitWidth(DAG, Offset, DL, 12819 RetVT.getScalarSizeInBits()); 12820 Opcode = AArch64ISD::GLDNT1; 12821 } 12822 12823 // In the case of non-temporal gather loads there's only one SVE instruction 12824 // per data-size: "scalar + vector", i.e. 12825 // * ldnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0] 12826 // Since we do have intrinsics that allow the arguments to be in a different 12827 // order, we may need to swap them to match the spec. 12828 if (Opcode == AArch64ISD::GLDNT1 && Offset.getValueType().isVector()) 12829 std::swap(Base, Offset); 12830 12831 // GLD{FF}1_IMM requires that the offset is an immediate that is: 12832 // * a multiple of #SizeInBytes, 12833 // * in the range [0, 31 x #SizeInBytes], 12834 // where #SizeInBytes is the size in bytes of the loaded items. For 12835 // immediates outside that range and non-immediate scalar offsets use GLD1 or 12836 // GLD1_UXTW instead. 12837 if (Opcode == AArch64ISD::GLD1_IMM || Opcode == AArch64ISD::GLDFF1_IMM) { 12838 if (!isValidImmForSVEVecImmAddrMode(Offset, 12839 RetVT.getScalarSizeInBits() / 8)) { 12840 if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy) 12841 Opcode = (Opcode == AArch64ISD::GLD1_IMM) ? AArch64ISD::GLD1_UXTW 12842 : AArch64ISD::GLDFF1_UXTW; 12843 else 12844 Opcode = (Opcode == AArch64ISD::GLD1_IMM) ? AArch64ISD::GLD1 12845 : AArch64ISD::GLDFF1; 12846 12847 std::swap(Base, Offset); 12848 } 12849 } 12850 12851 auto &TLI = DAG.getTargetLoweringInfo(); 12852 if (!TLI.isTypeLegal(Base.getValueType())) 12853 return SDValue(); 12854 12855 // Some gather load variants allow unpacked offsets, but only as nxv2i32 12856 // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to 12857 // nxv2i64. Legalize accordingly. 12858 if (!OnlyPackedOffsets && 12859 Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32) 12860 Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0); 12861 12862 // Return value type that is representable in hardware 12863 EVT HwRetVt = getSVEContainerType(RetVT); 12864 12865 // Keep the original output value type around - this is needed to be able to 12866 // select the correct instruction, e.g. LD1B, LD1H, LD1W and LD1D. For FP 12867 // values we want the integer equivalent, so just use HwRetVT. 12868 SDValue OutVT = DAG.getValueType(RetVT); 12869 if (RetVT.isFloatingPoint()) 12870 OutVT = DAG.getValueType(HwRetVt); 12871 12872 SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other); 12873 SDValue Ops[] = {N->getOperand(0), // Chain 12874 N->getOperand(2), // Pg 12875 Base, Offset, OutVT}; 12876 12877 SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops); 12878 SDValue LoadChain = SDValue(Load.getNode(), 1); 12879 12880 if (RetVT.isInteger() && (RetVT != HwRetVt)) 12881 Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0)); 12882 12883 // If the original return value was FP, bitcast accordingly. Doing it here 12884 // means that we can avoid adding TableGen patterns for FPs. 12885 if (RetVT.isFloatingPoint()) 12886 Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0)); 12887 12888 return DAG.getMergeValues({Load, LoadChain}, DL); 12889 } 12890 12891 static SDValue 12892 performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 12893 SelectionDAG &DAG) { 12894 if (DCI.isBeforeLegalizeOps()) 12895 return SDValue(); 12896 12897 SDValue Src = N->getOperand(0); 12898 unsigned Opc = Src->getOpcode(); 12899 12900 // SVE load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates 12901 // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes. 12902 unsigned NewOpc; 12903 unsigned MemVTOpNum = 4; 12904 switch (Opc) { 12905 case AArch64ISD::LDNF1: 12906 NewOpc = AArch64ISD::LDNF1S; 12907 MemVTOpNum = 3; 12908 break; 12909 case AArch64ISD::LDFF1: 12910 NewOpc = AArch64ISD::LDFF1S; 12911 MemVTOpNum = 3; 12912 break; 12913 case AArch64ISD::GLD1: 12914 NewOpc = AArch64ISD::GLD1S; 12915 break; 12916 case AArch64ISD::GLD1_SCALED: 12917 NewOpc = AArch64ISD::GLD1S_SCALED; 12918 break; 12919 case AArch64ISD::GLD1_SXTW: 12920 NewOpc = AArch64ISD::GLD1S_SXTW; 12921 break; 12922 case AArch64ISD::GLD1_SXTW_SCALED: 12923 NewOpc = AArch64ISD::GLD1S_SXTW_SCALED; 12924 break; 12925 case AArch64ISD::GLD1_UXTW: 12926 NewOpc = AArch64ISD::GLD1S_UXTW; 12927 break; 12928 case AArch64ISD::GLD1_UXTW_SCALED: 12929 NewOpc = AArch64ISD::GLD1S_UXTW_SCALED; 12930 break; 12931 case AArch64ISD::GLD1_IMM: 12932 NewOpc = AArch64ISD::GLD1S_IMM; 12933 break; 12934 case AArch64ISD::GLDFF1: 12935 NewOpc = AArch64ISD::GLDFF1S; 12936 break; 12937 case AArch64ISD::GLDFF1_SCALED: 12938 NewOpc = AArch64ISD::GLDFF1S_SCALED; 12939 break; 12940 case AArch64ISD::GLDFF1_SXTW: 12941 NewOpc = AArch64ISD::GLDFF1S_SXTW; 12942 break; 12943 case AArch64ISD::GLDFF1_SXTW_SCALED: 12944 NewOpc = AArch64ISD::GLDFF1S_SXTW_SCALED; 12945 break; 12946 case AArch64ISD::GLDFF1_UXTW: 12947 NewOpc = AArch64ISD::GLDFF1S_UXTW; 12948 break; 12949 case AArch64ISD::GLDFF1_UXTW_SCALED: 12950 NewOpc = AArch64ISD::GLDFF1S_UXTW_SCALED; 12951 break; 12952 case AArch64ISD::GLDFF1_IMM: 12953 NewOpc = AArch64ISD::GLDFF1S_IMM; 12954 break; 12955 case AArch64ISD::GLDNT1: 12956 NewOpc = AArch64ISD::GLDNT1S; 12957 break; 12958 default: 12959 return SDValue(); 12960 } 12961 12962 EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 12963 EVT SrcMemVT = cast<VTSDNode>(Src->getOperand(MemVTOpNum))->getVT(); 12964 12965 if ((SignExtSrcVT != SrcMemVT) || !Src.hasOneUse()) 12966 return SDValue(); 12967 12968 EVT DstVT = N->getValueType(0); 12969 SDVTList VTs = DAG.getVTList(DstVT, MVT::Other); 12970 12971 SmallVector<SDValue, 5> Ops; 12972 for (unsigned I = 0; I < Src->getNumOperands(); ++I) 12973 Ops.push_back(Src->getOperand(I)); 12974 12975 SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops); 12976 DCI.CombineTo(N, ExtLoad); 12977 DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1)); 12978 12979 // Return N so it doesn't get rechecked 12980 return SDValue(N, 0); 12981 } 12982 12983 /// Legalize the gather prefetch (scalar + vector addressing mode) when the 12984 /// offset vector is an unpacked 32-bit scalable vector. The other cases (Offset 12985 /// != nxv2i32) do not need legalization. 12986 static SDValue legalizeSVEGatherPrefetchOffsVec(SDNode *N, SelectionDAG &DAG) { 12987 const unsigned OffsetPos = 4; 12988 SDValue Offset = N->getOperand(OffsetPos); 12989 12990 // Not an unpacked vector, bail out. 12991 if (Offset.getValueType().getSimpleVT().SimpleTy != MVT::nxv2i32) 12992 return SDValue(); 12993 12994 // Extend the unpacked offset vector to 64-bit lanes. 12995 SDLoc DL(N); 12996 Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset); 12997 SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end()); 12998 // Replace the offset operand with the 64-bit one. 12999 Ops[OffsetPos] = Offset; 13000 13001 return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops); 13002 } 13003 13004 /// Combines a node carrying the intrinsic `aarch64_sve_prf_gather<T>` into a 13005 /// node that uses `aarch64_sve_prf_gather<T>_scaled_uxtw` when the scalar 13006 /// offset passed to `aarch64_sve_prf_gather<T>` is not a valid immediate for 13007 /// the sve gather prefetch instruction with vector plus immediate addressing 13008 /// mode. 13009 static SDValue combineSVEPrefetchVecBaseImmOff(SDNode *N, SelectionDAG &DAG, 13010 unsigned NewIID, 13011 unsigned ScalarSizeInBytes) { 13012 const unsigned ImmPos = 4, OffsetPos = 3; 13013 // No need to combine the node if the immediate is valid... 13014 if (isValidImmForSVEVecImmAddrMode(N->getOperand(ImmPos), ScalarSizeInBytes)) 13015 return SDValue(); 13016 13017 // ...otherwise swap the offset base with the offset... 13018 SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end()); 13019 std::swap(Ops[ImmPos], Ops[OffsetPos]); 13020 // ...and remap the intrinsic `aarch64_sve_prf_gather<T>` to 13021 // `aarch64_sve_prf_gather<T>_scaled_uxtw`. 13022 SDLoc DL(N); 13023 Ops[1] = DAG.getConstant(NewIID, DL, MVT::i64); 13024 13025 return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops); 13026 } 13027 13028 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N, 13029 DAGCombinerInfo &DCI) const { 13030 SelectionDAG &DAG = DCI.DAG; 13031 switch (N->getOpcode()) { 13032 default: 13033 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n"); 13034 break; 13035 case ISD::ADD: 13036 case ISD::SUB: 13037 return performAddSubLongCombine(N, DCI, DAG); 13038 case ISD::XOR: 13039 return performXorCombine(N, DAG, DCI, Subtarget); 13040 case ISD::MUL: 13041 return performMulCombine(N, DAG, DCI, Subtarget); 13042 case ISD::SINT_TO_FP: 13043 case ISD::UINT_TO_FP: 13044 return performIntToFpCombine(N, DAG, Subtarget); 13045 case ISD::FP_TO_SINT: 13046 case ISD::FP_TO_UINT: 13047 return performFpToIntCombine(N, DAG, DCI, Subtarget); 13048 case ISD::FDIV: 13049 return performFDivCombine(N, DAG, DCI, Subtarget); 13050 case ISD::OR: 13051 return performORCombine(N, DCI, Subtarget); 13052 case ISD::AND: 13053 return performANDCombine(N, DCI); 13054 case ISD::SRL: 13055 return performSRLCombine(N, DCI); 13056 case ISD::INTRINSIC_WO_CHAIN: 13057 return performIntrinsicCombine(N, DCI, Subtarget); 13058 case ISD::ANY_EXTEND: 13059 case ISD::ZERO_EXTEND: 13060 case ISD::SIGN_EXTEND: 13061 return performExtendCombine(N, DCI, DAG); 13062 case ISD::SIGN_EXTEND_INREG: 13063 return performSignExtendInRegCombine(N, DCI, DAG); 13064 case ISD::CONCAT_VECTORS: 13065 return performConcatVectorsCombine(N, DCI, DAG); 13066 case ISD::SELECT: 13067 return performSelectCombine(N, DCI); 13068 case ISD::VSELECT: 13069 return performVSelectCombine(N, DCI.DAG); 13070 case ISD::LOAD: 13071 if (performTBISimplification(N->getOperand(1), DCI, DAG)) 13072 return SDValue(N, 0); 13073 break; 13074 case ISD::STORE: 13075 return performSTORECombine(N, DCI, DAG, Subtarget); 13076 case AArch64ISD::BRCOND: 13077 return performBRCONDCombine(N, DCI, DAG); 13078 case AArch64ISD::TBNZ: 13079 case AArch64ISD::TBZ: 13080 return performTBZCombine(N, DCI, DAG); 13081 case AArch64ISD::CSEL: 13082 return performCONDCombine(N, DCI, DAG, 2, 3); 13083 case AArch64ISD::DUP: 13084 return performPostLD1Combine(N, DCI, false); 13085 case AArch64ISD::NVCAST: 13086 return performNVCASTCombine(N); 13087 case ISD::INSERT_VECTOR_ELT: 13088 return performPostLD1Combine(N, DCI, true); 13089 case ISD::INTRINSIC_VOID: 13090 case ISD::INTRINSIC_W_CHAIN: 13091 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 13092 case Intrinsic::aarch64_sve_prfb_gather: 13093 return combineSVEPrefetchVecBaseImmOff( 13094 N, DAG, Intrinsic::aarch64_sve_prfb_gather_scaled_uxtw, 13095 1 /*=ScalarSizeInBytes*/); 13096 case Intrinsic::aarch64_sve_prfh_gather: 13097 return combineSVEPrefetchVecBaseImmOff( 13098 N, DAG, Intrinsic::aarch64_sve_prfh_gather_scaled_uxtw, 13099 2 /*=ScalarSizeInBytes*/); 13100 case Intrinsic::aarch64_sve_prfw_gather: 13101 return combineSVEPrefetchVecBaseImmOff( 13102 N, DAG, Intrinsic::aarch64_sve_prfw_gather_scaled_uxtw, 13103 4 /*=ScalarSizeInBytes*/); 13104 case Intrinsic::aarch64_sve_prfd_gather: 13105 return combineSVEPrefetchVecBaseImmOff( 13106 N, DAG, Intrinsic::aarch64_sve_prfd_gather_scaled_uxtw, 13107 8 /*=ScalarSizeInBytes*/); 13108 case Intrinsic::aarch64_sve_prfb_gather_scaled_uxtw: 13109 case Intrinsic::aarch64_sve_prfb_gather_scaled_sxtw: 13110 case Intrinsic::aarch64_sve_prfh_gather_scaled_uxtw: 13111 case Intrinsic::aarch64_sve_prfh_gather_scaled_sxtw: 13112 case Intrinsic::aarch64_sve_prfw_gather_scaled_uxtw: 13113 case Intrinsic::aarch64_sve_prfw_gather_scaled_sxtw: 13114 case Intrinsic::aarch64_sve_prfd_gather_scaled_uxtw: 13115 case Intrinsic::aarch64_sve_prfd_gather_scaled_sxtw: 13116 return legalizeSVEGatherPrefetchOffsVec(N, DAG); 13117 case Intrinsic::aarch64_neon_ld2: 13118 case Intrinsic::aarch64_neon_ld3: 13119 case Intrinsic::aarch64_neon_ld4: 13120 case Intrinsic::aarch64_neon_ld1x2: 13121 case Intrinsic::aarch64_neon_ld1x3: 13122 case Intrinsic::aarch64_neon_ld1x4: 13123 case Intrinsic::aarch64_neon_ld2lane: 13124 case Intrinsic::aarch64_neon_ld3lane: 13125 case Intrinsic::aarch64_neon_ld4lane: 13126 case Intrinsic::aarch64_neon_ld2r: 13127 case Intrinsic::aarch64_neon_ld3r: 13128 case Intrinsic::aarch64_neon_ld4r: 13129 case Intrinsic::aarch64_neon_st2: 13130 case Intrinsic::aarch64_neon_st3: 13131 case Intrinsic::aarch64_neon_st4: 13132 case Intrinsic::aarch64_neon_st1x2: 13133 case Intrinsic::aarch64_neon_st1x3: 13134 case Intrinsic::aarch64_neon_st1x4: 13135 case Intrinsic::aarch64_neon_st2lane: 13136 case Intrinsic::aarch64_neon_st3lane: 13137 case Intrinsic::aarch64_neon_st4lane: 13138 return performNEONPostLDSTCombine(N, DCI, DAG); 13139 case Intrinsic::aarch64_sve_ld1: 13140 case Intrinsic::aarch64_sve_ldnt1: 13141 return performLD1Combine(N, DAG); 13142 case Intrinsic::aarch64_sve_ldnt1_gather_scalar_offset: 13143 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1); 13144 case Intrinsic::aarch64_sve_ldnt1_gather: 13145 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1); 13146 case Intrinsic::aarch64_sve_ldnt1_gather_index: 13147 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_INDEX); 13148 case Intrinsic::aarch64_sve_ldnt1_gather_uxtw: 13149 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1); 13150 case Intrinsic::aarch64_sve_ldnf1: 13151 return performLDNF1Combine(N, DAG, AArch64ISD::LDNF1); 13152 case Intrinsic::aarch64_sve_ldff1: 13153 return performLDNF1Combine(N, DAG, AArch64ISD::LDFF1); 13154 case Intrinsic::aarch64_sve_st1: 13155 case Intrinsic::aarch64_sve_stnt1: 13156 return performST1Combine(N, DAG); 13157 case Intrinsic::aarch64_sve_stnt1_scatter_scalar_offset: 13158 return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1); 13159 case Intrinsic::aarch64_sve_stnt1_scatter_uxtw: 13160 return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1); 13161 case Intrinsic::aarch64_sve_stnt1_scatter: 13162 return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1); 13163 case Intrinsic::aarch64_sve_stnt1_scatter_index: 13164 return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_INDEX); 13165 case Intrinsic::aarch64_sve_ld1_gather: 13166 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1); 13167 case Intrinsic::aarch64_sve_ld1_gather_index: 13168 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SCALED); 13169 case Intrinsic::aarch64_sve_ld1_gather_sxtw: 13170 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SXTW, 13171 /*OnlyPackedOffsets=*/false); 13172 case Intrinsic::aarch64_sve_ld1_gather_uxtw: 13173 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_UXTW, 13174 /*OnlyPackedOffsets=*/false); 13175 case Intrinsic::aarch64_sve_ld1_gather_sxtw_index: 13176 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SXTW_SCALED, 13177 /*OnlyPackedOffsets=*/false); 13178 case Intrinsic::aarch64_sve_ld1_gather_uxtw_index: 13179 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_UXTW_SCALED, 13180 /*OnlyPackedOffsets=*/false); 13181 case Intrinsic::aarch64_sve_ld1_gather_scalar_offset: 13182 return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_IMM); 13183 case Intrinsic::aarch64_sve_ldff1_gather: 13184 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1); 13185 case Intrinsic::aarch64_sve_ldff1_gather_index: 13186 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_SCALED); 13187 case Intrinsic::aarch64_sve_ldff1_gather_sxtw: 13188 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_SXTW, 13189 /*OnlyPackedOffsets=*/false); 13190 case Intrinsic::aarch64_sve_ldff1_gather_uxtw: 13191 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_UXTW, 13192 /*OnlyPackedOffsets=*/false); 13193 case Intrinsic::aarch64_sve_ldff1_gather_sxtw_index: 13194 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_SXTW_SCALED, 13195 /*OnlyPackedOffsets=*/false); 13196 case Intrinsic::aarch64_sve_ldff1_gather_uxtw_index: 13197 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_UXTW_SCALED, 13198 /*OnlyPackedOffsets=*/false); 13199 case Intrinsic::aarch64_sve_ldff1_gather_scalar_offset: 13200 return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_IMM); 13201 case Intrinsic::aarch64_sve_st1_scatter: 13202 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1); 13203 case Intrinsic::aarch64_sve_st1_scatter_index: 13204 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SCALED); 13205 case Intrinsic::aarch64_sve_st1_scatter_sxtw: 13206 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SXTW, 13207 /*OnlyPackedOffsets=*/false); 13208 case Intrinsic::aarch64_sve_st1_scatter_uxtw: 13209 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_UXTW, 13210 /*OnlyPackedOffsets=*/false); 13211 case Intrinsic::aarch64_sve_st1_scatter_sxtw_index: 13212 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SXTW_SCALED, 13213 /*OnlyPackedOffsets=*/false); 13214 case Intrinsic::aarch64_sve_st1_scatter_uxtw_index: 13215 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_UXTW_SCALED, 13216 /*OnlyPackedOffsets=*/false); 13217 case Intrinsic::aarch64_sve_st1_scatter_scalar_offset: 13218 return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_IMM); 13219 default: 13220 break; 13221 } 13222 break; 13223 case ISD::GlobalAddress: 13224 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine()); 13225 } 13226 return SDValue(); 13227 } 13228 13229 // Check if the return value is used as only a return value, as otherwise 13230 // we can't perform a tail-call. In particular, we need to check for 13231 // target ISD nodes that are returns and any other "odd" constructs 13232 // that the generic analysis code won't necessarily catch. 13233 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N, 13234 SDValue &Chain) const { 13235 if (N->getNumValues() != 1) 13236 return false; 13237 if (!N->hasNUsesOfValue(1, 0)) 13238 return false; 13239 13240 SDValue TCChain = Chain; 13241 SDNode *Copy = *N->use_begin(); 13242 if (Copy->getOpcode() == ISD::CopyToReg) { 13243 // If the copy has a glue operand, we conservatively assume it isn't safe to 13244 // perform a tail call. 13245 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() == 13246 MVT::Glue) 13247 return false; 13248 TCChain = Copy->getOperand(0); 13249 } else if (Copy->getOpcode() != ISD::FP_EXTEND) 13250 return false; 13251 13252 bool HasRet = false; 13253 for (SDNode *Node : Copy->uses()) { 13254 if (Node->getOpcode() != AArch64ISD::RET_FLAG) 13255 return false; 13256 HasRet = true; 13257 } 13258 13259 if (!HasRet) 13260 return false; 13261 13262 Chain = TCChain; 13263 return true; 13264 } 13265 13266 // Return whether the an instruction can potentially be optimized to a tail 13267 // call. This will cause the optimizers to attempt to move, or duplicate, 13268 // return instructions to help enable tail call optimizations for this 13269 // instruction. 13270 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 13271 return CI->isTailCall(); 13272 } 13273 13274 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base, 13275 SDValue &Offset, 13276 ISD::MemIndexedMode &AM, 13277 bool &IsInc, 13278 SelectionDAG &DAG) const { 13279 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) 13280 return false; 13281 13282 Base = Op->getOperand(0); 13283 // All of the indexed addressing mode instructions take a signed 13284 // 9 bit immediate offset. 13285 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) { 13286 int64_t RHSC = RHS->getSExtValue(); 13287 if (Op->getOpcode() == ISD::SUB) 13288 RHSC = -(uint64_t)RHSC; 13289 if (!isInt<9>(RHSC)) 13290 return false; 13291 IsInc = (Op->getOpcode() == ISD::ADD); 13292 Offset = Op->getOperand(1); 13293 return true; 13294 } 13295 return false; 13296 } 13297 13298 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 13299 SDValue &Offset, 13300 ISD::MemIndexedMode &AM, 13301 SelectionDAG &DAG) const { 13302 EVT VT; 13303 SDValue Ptr; 13304 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 13305 VT = LD->getMemoryVT(); 13306 Ptr = LD->getBasePtr(); 13307 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 13308 VT = ST->getMemoryVT(); 13309 Ptr = ST->getBasePtr(); 13310 } else 13311 return false; 13312 13313 bool IsInc; 13314 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG)) 13315 return false; 13316 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC; 13317 return true; 13318 } 13319 13320 bool AArch64TargetLowering::getPostIndexedAddressParts( 13321 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset, 13322 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const { 13323 EVT VT; 13324 SDValue Ptr; 13325 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 13326 VT = LD->getMemoryVT(); 13327 Ptr = LD->getBasePtr(); 13328 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 13329 VT = ST->getMemoryVT(); 13330 Ptr = ST->getBasePtr(); 13331 } else 13332 return false; 13333 13334 bool IsInc; 13335 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG)) 13336 return false; 13337 // Post-indexing updates the base, so it's not a valid transform 13338 // if that's not the same as the load's pointer. 13339 if (Ptr != Base) 13340 return false; 13341 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC; 13342 return true; 13343 } 13344 13345 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results, 13346 SelectionDAG &DAG) { 13347 SDLoc DL(N); 13348 SDValue Op = N->getOperand(0); 13349 13350 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16) 13351 return; 13352 13353 Op = SDValue( 13354 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32, 13355 DAG.getUNDEF(MVT::i32), Op, 13356 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 13357 0); 13358 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op); 13359 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op)); 13360 } 13361 13362 static void ReplaceReductionResults(SDNode *N, 13363 SmallVectorImpl<SDValue> &Results, 13364 SelectionDAG &DAG, unsigned InterOp, 13365 unsigned AcrossOp) { 13366 EVT LoVT, HiVT; 13367 SDValue Lo, Hi; 13368 SDLoc dl(N); 13369 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 13370 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0); 13371 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi); 13372 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal); 13373 Results.push_back(SplitVal); 13374 } 13375 13376 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) { 13377 SDLoc DL(N); 13378 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N); 13379 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, 13380 DAG.getNode(ISD::SRL, DL, MVT::i128, N, 13381 DAG.getConstant(64, DL, MVT::i64))); 13382 return std::make_pair(Lo, Hi); 13383 } 13384 13385 // Create an even/odd pair of X registers holding integer value V. 13386 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 13387 SDLoc dl(V.getNode()); 13388 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64); 13389 SDValue VHi = DAG.getAnyExtOrTrunc( 13390 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)), 13391 dl, MVT::i64); 13392 if (DAG.getDataLayout().isBigEndian()) 13393 std::swap (VLo, VHi); 13394 SDValue RegClass = 13395 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32); 13396 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32); 13397 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32); 13398 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 13399 return SDValue( 13400 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 13401 } 13402 13403 static void ReplaceCMP_SWAP_128Results(SDNode *N, 13404 SmallVectorImpl<SDValue> &Results, 13405 SelectionDAG &DAG, 13406 const AArch64Subtarget *Subtarget) { 13407 assert(N->getValueType(0) == MVT::i128 && 13408 "AtomicCmpSwap on types less than 128 should be legal"); 13409 13410 if (Subtarget->hasLSE()) { 13411 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type, 13412 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG. 13413 SDValue Ops[] = { 13414 createGPRPairNode(DAG, N->getOperand(2)), // Compare value 13415 createGPRPairNode(DAG, N->getOperand(3)), // Store value 13416 N->getOperand(1), // Ptr 13417 N->getOperand(0), // Chain in 13418 }; 13419 13420 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 13421 13422 unsigned Opcode; 13423 switch (MemOp->getOrdering()) { 13424 case AtomicOrdering::Monotonic: 13425 Opcode = AArch64::CASPX; 13426 break; 13427 case AtomicOrdering::Acquire: 13428 Opcode = AArch64::CASPAX; 13429 break; 13430 case AtomicOrdering::Release: 13431 Opcode = AArch64::CASPLX; 13432 break; 13433 case AtomicOrdering::AcquireRelease: 13434 case AtomicOrdering::SequentiallyConsistent: 13435 Opcode = AArch64::CASPALX; 13436 break; 13437 default: 13438 llvm_unreachable("Unexpected ordering!"); 13439 } 13440 13441 MachineSDNode *CmpSwap = DAG.getMachineNode( 13442 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops); 13443 DAG.setNodeMemRefs(CmpSwap, {MemOp}); 13444 13445 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64; 13446 if (DAG.getDataLayout().isBigEndian()) 13447 std::swap(SubReg1, SubReg2); 13448 SDValue Lo = DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64, 13449 SDValue(CmpSwap, 0)); 13450 SDValue Hi = DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64, 13451 SDValue(CmpSwap, 0)); 13452 Results.push_back( 13453 DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, Lo, Hi)); 13454 Results.push_back(SDValue(CmpSwap, 1)); // Chain out 13455 return; 13456 } 13457 13458 auto Desired = splitInt128(N->getOperand(2), DAG); 13459 auto New = splitInt128(N->getOperand(3), DAG); 13460 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second, 13461 New.first, New.second, N->getOperand(0)}; 13462 SDNode *CmpSwap = DAG.getMachineNode( 13463 AArch64::CMP_SWAP_128, SDLoc(N), 13464 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops); 13465 13466 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 13467 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp}); 13468 13469 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, 13470 SDValue(CmpSwap, 0), SDValue(CmpSwap, 1))); 13471 Results.push_back(SDValue(CmpSwap, 3)); 13472 } 13473 13474 void AArch64TargetLowering::ReplaceNodeResults( 13475 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const { 13476 switch (N->getOpcode()) { 13477 default: 13478 llvm_unreachable("Don't know how to custom expand this"); 13479 case ISD::BITCAST: 13480 ReplaceBITCASTResults(N, Results, DAG); 13481 return; 13482 case ISD::VECREDUCE_ADD: 13483 case ISD::VECREDUCE_SMAX: 13484 case ISD::VECREDUCE_SMIN: 13485 case ISD::VECREDUCE_UMAX: 13486 case ISD::VECREDUCE_UMIN: 13487 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG)); 13488 return; 13489 13490 case AArch64ISD::SADDV: 13491 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV); 13492 return; 13493 case AArch64ISD::UADDV: 13494 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV); 13495 return; 13496 case AArch64ISD::SMINV: 13497 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV); 13498 return; 13499 case AArch64ISD::UMINV: 13500 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV); 13501 return; 13502 case AArch64ISD::SMAXV: 13503 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV); 13504 return; 13505 case AArch64ISD::UMAXV: 13506 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV); 13507 return; 13508 case ISD::FP_TO_UINT: 13509 case ISD::FP_TO_SINT: 13510 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion"); 13511 // Let normal code take care of it by not adding anything to Results. 13512 return; 13513 case ISD::ATOMIC_CMP_SWAP: 13514 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget); 13515 return; 13516 case ISD::LOAD: { 13517 assert(SDValue(N, 0).getValueType() == MVT::i128 && 13518 "unexpected load's value type"); 13519 LoadSDNode *LoadNode = cast<LoadSDNode>(N); 13520 if (!LoadNode->isVolatile() || LoadNode->getMemoryVT() != MVT::i128) { 13521 // Non-volatile loads are optimized later in AArch64's load/store 13522 // optimizer. 13523 return; 13524 } 13525 13526 SDValue Result = DAG.getMemIntrinsicNode( 13527 AArch64ISD::LDP, SDLoc(N), 13528 DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}), 13529 {LoadNode->getChain(), LoadNode->getBasePtr()}, LoadNode->getMemoryVT(), 13530 LoadNode->getMemOperand()); 13531 13532 SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, 13533 Result.getValue(0), Result.getValue(1)); 13534 Results.append({Pair, Result.getValue(2) /* Chain */}); 13535 return; 13536 } 13537 case ISD::INTRINSIC_WO_CHAIN: { 13538 EVT VT = N->getValueType(0); 13539 assert((VT == MVT::i8 || VT == MVT::i16) && 13540 "custom lowering for unexpected type"); 13541 13542 ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0)); 13543 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 13544 switch (IntID) { 13545 default: 13546 return; 13547 case Intrinsic::aarch64_sve_clasta_n: { 13548 SDLoc DL(N); 13549 auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2)); 13550 auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32, 13551 N->getOperand(1), Op2, N->getOperand(3)); 13552 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V)); 13553 return; 13554 } 13555 case Intrinsic::aarch64_sve_clastb_n: { 13556 SDLoc DL(N); 13557 auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2)); 13558 auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32, 13559 N->getOperand(1), Op2, N->getOperand(3)); 13560 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V)); 13561 return; 13562 } 13563 case Intrinsic::aarch64_sve_lasta: { 13564 SDLoc DL(N); 13565 auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32, 13566 N->getOperand(1), N->getOperand(2)); 13567 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V)); 13568 return; 13569 } 13570 case Intrinsic::aarch64_sve_lastb: { 13571 SDLoc DL(N); 13572 auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32, 13573 N->getOperand(1), N->getOperand(2)); 13574 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V)); 13575 return; 13576 } 13577 } 13578 } 13579 } 13580 } 13581 13582 bool AArch64TargetLowering::useLoadStackGuardNode() const { 13583 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia()) 13584 return TargetLowering::useLoadStackGuardNode(); 13585 return true; 13586 } 13587 13588 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const { 13589 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 13590 // reciprocal if there are three or more FDIVs. 13591 return 3; 13592 } 13593 13594 TargetLoweringBase::LegalizeTypeAction 13595 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const { 13596 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8, 13597 // v4i16, v2i32 instead of to promote. 13598 if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 || 13599 VT == MVT::v1f32) 13600 return TypeWidenVector; 13601 13602 return TargetLoweringBase::getPreferredVectorAction(VT); 13603 } 13604 13605 // Loads and stores less than 128-bits are already atomic; ones above that 13606 // are doomed anyway, so defer to the default libcall and blame the OS when 13607 // things go wrong. 13608 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 13609 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 13610 return Size == 128; 13611 } 13612 13613 // Loads and stores less than 128-bits are already atomic; ones above that 13614 // are doomed anyway, so defer to the default libcall and blame the OS when 13615 // things go wrong. 13616 TargetLowering::AtomicExpansionKind 13617 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 13618 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 13619 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None; 13620 } 13621 13622 // For the real atomic operations, we have ldxr/stxr up to 128 bits, 13623 TargetLowering::AtomicExpansionKind 13624 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 13625 if (AI->isFloatingPointOperation()) 13626 return AtomicExpansionKind::CmpXChg; 13627 13628 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 13629 if (Size > 128) return AtomicExpansionKind::None; 13630 // Nand not supported in LSE. 13631 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC; 13632 // Leave 128 bits to LLSC. 13633 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC; 13634 } 13635 13636 TargetLowering::AtomicExpansionKind 13637 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR( 13638 AtomicCmpXchgInst *AI) const { 13639 // If subtarget has LSE, leave cmpxchg intact for codegen. 13640 if (Subtarget->hasLSE()) 13641 return AtomicExpansionKind::None; 13642 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 13643 // implement cmpxchg without spilling. If the address being exchanged is also 13644 // on the stack and close enough to the spill slot, this can lead to a 13645 // situation where the monitor always gets cleared and the atomic operation 13646 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 13647 if (getTargetMachine().getOptLevel() == 0) 13648 return AtomicExpansionKind::None; 13649 return AtomicExpansionKind::LLSC; 13650 } 13651 13652 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 13653 AtomicOrdering Ord) const { 13654 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13655 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 13656 bool IsAcquire = isAcquireOrStronger(Ord); 13657 13658 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd 13659 // intrinsic must return {i64, i64} and we have to recombine them into a 13660 // single i128 here. 13661 if (ValTy->getPrimitiveSizeInBits() == 128) { 13662 Intrinsic::ID Int = 13663 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp; 13664 Function *Ldxr = Intrinsic::getDeclaration(M, Int); 13665 13666 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 13667 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi"); 13668 13669 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 13670 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 13671 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 13672 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 13673 return Builder.CreateOr( 13674 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 13675 } 13676 13677 Type *Tys[] = { Addr->getType() }; 13678 Intrinsic::ID Int = 13679 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr; 13680 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys); 13681 13682 Type *EltTy = cast<PointerType>(Addr->getType())->getElementType(); 13683 13684 const DataLayout &DL = M->getDataLayout(); 13685 IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy)); 13686 Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy); 13687 13688 return Builder.CreateBitCast(Trunc, EltTy); 13689 } 13690 13691 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 13692 IRBuilder<> &Builder) const { 13693 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13694 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex)); 13695 } 13696 13697 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder, 13698 Value *Val, Value *Addr, 13699 AtomicOrdering Ord) const { 13700 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 13701 bool IsRelease = isReleaseOrStronger(Ord); 13702 13703 // Since the intrinsics must have legal type, the i128 intrinsics take two 13704 // parameters: "i64, i64". We must marshal Val into the appropriate form 13705 // before the call. 13706 if (Val->getType()->getPrimitiveSizeInBits() == 128) { 13707 Intrinsic::ID Int = 13708 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp; 13709 Function *Stxr = Intrinsic::getDeclaration(M, Int); 13710 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 13711 13712 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo"); 13713 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi"); 13714 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 13715 return Builder.CreateCall(Stxr, {Lo, Hi, Addr}); 13716 } 13717 13718 Intrinsic::ID Int = 13719 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr; 13720 Type *Tys[] = { Addr->getType() }; 13721 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys); 13722 13723 const DataLayout &DL = M->getDataLayout(); 13724 IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType())); 13725 Val = Builder.CreateBitCast(Val, IntValTy); 13726 13727 return Builder.CreateCall(Stxr, 13728 {Builder.CreateZExtOrBitCast( 13729 Val, Stxr->getFunctionType()->getParamType(0)), 13730 Addr}); 13731 } 13732 13733 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters( 13734 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 13735 return Ty->isArrayTy(); 13736 } 13737 13738 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &, 13739 EVT) const { 13740 return false; 13741 } 13742 13743 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) { 13744 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 13745 Function *ThreadPointerFunc = 13746 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer); 13747 return IRB.CreatePointerCast( 13748 IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc), 13749 Offset), 13750 IRB.getInt8PtrTy()->getPointerTo(0)); 13751 } 13752 13753 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const { 13754 // Android provides a fixed TLS slot for the stack cookie. See the definition 13755 // of TLS_SLOT_STACK_GUARD in 13756 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 13757 if (Subtarget->isTargetAndroid()) 13758 return UseTlsOffset(IRB, 0x28); 13759 13760 // Fuchsia is similar. 13761 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value. 13762 if (Subtarget->isTargetFuchsia()) 13763 return UseTlsOffset(IRB, -0x10); 13764 13765 return TargetLowering::getIRStackGuard(IRB); 13766 } 13767 13768 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const { 13769 // MSVC CRT provides functionalities for stack protection. 13770 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) { 13771 // MSVC CRT has a global variable holding security cookie. 13772 M.getOrInsertGlobal("__security_cookie", 13773 Type::getInt8PtrTy(M.getContext())); 13774 13775 // MSVC CRT has a function to validate security cookie. 13776 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction( 13777 "__security_check_cookie", Type::getVoidTy(M.getContext()), 13778 Type::getInt8PtrTy(M.getContext())); 13779 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) { 13780 F->setCallingConv(CallingConv::Win64); 13781 F->addAttribute(1, Attribute::AttrKind::InReg); 13782 } 13783 return; 13784 } 13785 TargetLowering::insertSSPDeclarations(M); 13786 } 13787 13788 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const { 13789 // MSVC CRT has a global variable holding security cookie. 13790 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 13791 return M.getGlobalVariable("__security_cookie"); 13792 return TargetLowering::getSDagStackGuard(M); 13793 } 13794 13795 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const { 13796 // MSVC CRT has a function to validate security cookie. 13797 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 13798 return M.getFunction("__security_check_cookie"); 13799 return TargetLowering::getSSPStackGuardCheck(M); 13800 } 13801 13802 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const { 13803 // Android provides a fixed TLS slot for the SafeStack pointer. See the 13804 // definition of TLS_SLOT_SAFESTACK in 13805 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 13806 if (Subtarget->isTargetAndroid()) 13807 return UseTlsOffset(IRB, 0x48); 13808 13809 // Fuchsia is similar. 13810 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value. 13811 if (Subtarget->isTargetFuchsia()) 13812 return UseTlsOffset(IRB, -0x8); 13813 13814 return TargetLowering::getSafeStackPointerLocation(IRB); 13815 } 13816 13817 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial( 13818 const Instruction &AndI) const { 13819 // Only sink 'and' mask to cmp use block if it is masking a single bit, since 13820 // this is likely to be fold the and/cmp/br into a single tbz instruction. It 13821 // may be beneficial to sink in other cases, but we would have to check that 13822 // the cmp would not get folded into the br to form a cbz for these to be 13823 // beneficial. 13824 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1)); 13825 if (!Mask) 13826 return false; 13827 return Mask->getValue().isPowerOf2(); 13828 } 13829 13830 bool AArch64TargetLowering:: 13831 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 13832 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y, 13833 unsigned OldShiftOpcode, unsigned NewShiftOpcode, 13834 SelectionDAG &DAG) const { 13835 // Does baseline recommend not to perform the fold by default? 13836 if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 13837 X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG)) 13838 return false; 13839 // Else, if this is a vector shift, prefer 'shl'. 13840 return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL; 13841 } 13842 13843 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG, 13844 SDNode *N) const { 13845 if (DAG.getMachineFunction().getFunction().hasMinSize() && 13846 !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin()) 13847 return false; 13848 return true; 13849 } 13850 13851 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 13852 // Update IsSplitCSR in AArch64unctionInfo. 13853 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>(); 13854 AFI->setIsSplitCSR(true); 13855 } 13856 13857 void AArch64TargetLowering::insertCopiesSplitCSR( 13858 MachineBasicBlock *Entry, 13859 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 13860 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 13861 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 13862 if (!IStart) 13863 return; 13864 13865 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 13866 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 13867 MachineBasicBlock::iterator MBBI = Entry->begin(); 13868 for (const MCPhysReg *I = IStart; *I; ++I) { 13869 const TargetRegisterClass *RC = nullptr; 13870 if (AArch64::GPR64RegClass.contains(*I)) 13871 RC = &AArch64::GPR64RegClass; 13872 else if (AArch64::FPR64RegClass.contains(*I)) 13873 RC = &AArch64::FPR64RegClass; 13874 else 13875 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 13876 13877 Register NewVR = MRI->createVirtualRegister(RC); 13878 // Create copy from CSR to a virtual register. 13879 // FIXME: this currently does not emit CFI pseudo-instructions, it works 13880 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 13881 // nounwind. If we want to generalize this later, we may need to emit 13882 // CFI pseudo-instructions. 13883 assert(Entry->getParent()->getFunction().hasFnAttribute( 13884 Attribute::NoUnwind) && 13885 "Function should be nounwind in insertCopiesSplitCSR!"); 13886 Entry->addLiveIn(*I); 13887 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 13888 .addReg(*I); 13889 13890 // Insert the copy-back instructions right before the terminator. 13891 for (auto *Exit : Exits) 13892 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 13893 TII->get(TargetOpcode::COPY), *I) 13894 .addReg(NewVR); 13895 } 13896 } 13897 13898 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const { 13899 // Integer division on AArch64 is expensive. However, when aggressively 13900 // optimizing for code size, we prefer to use a div instruction, as it is 13901 // usually smaller than the alternative sequence. 13902 // The exception to this is vector division. Since AArch64 doesn't have vector 13903 // integer division, leaving the division as-is is a loss even in terms of 13904 // size, because it will have to be scalarized, while the alternative code 13905 // sequence can be performed in vector form. 13906 bool OptSize = 13907 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize); 13908 return OptSize && !VT.isVector(); 13909 } 13910 13911 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const { 13912 // We want inc-of-add for scalars and sub-of-not for vectors. 13913 return VT.isScalarInteger(); 13914 } 13915 13916 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const { 13917 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint(); 13918 } 13919 13920 unsigned 13921 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const { 13922 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows()) 13923 return getPointerTy(DL).getSizeInBits(); 13924 13925 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32; 13926 } 13927 13928 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const { 13929 MF.getFrameInfo().computeMaxCallFrameSize(MF); 13930 TargetLoweringBase::finalizeLowering(MF); 13931 } 13932 13933 // Unlike X86, we let frame lowering assign offsets to all catch objects. 13934 bool AArch64TargetLowering::needsFixedCatchObjects() const { 13935 return false; 13936 } 13937 13938 bool AArch64TargetLowering::shouldLocalize( 13939 const MachineInstr &MI, const TargetTransformInfo *TTI) const { 13940 if (MI.getOpcode() == TargetOpcode::G_GLOBAL_VALUE) { 13941 // On Darwin, TLS global vars get selected into function calls, which 13942 // we don't want localized, as they can get moved into the middle of a 13943 // another call sequence. 13944 const GlobalValue &GV = *MI.getOperand(1).getGlobal(); 13945 if (GV.isThreadLocal() && Subtarget->isTargetMachO()) 13946 return false; 13947 } 13948 return TargetLoweringBase::shouldLocalize(MI, TTI); 13949 } 13950