1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the AArch64TargetLowering class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "AArch64ISelLowering.h" 15 #include "AArch64CallingConvention.h" 16 #include "AArch64MachineFunctionInfo.h" 17 #include "AArch64PerfectShuffle.h" 18 #include "AArch64Subtarget.h" 19 #include "AArch64TargetMachine.h" 20 #include "AArch64TargetObjectFile.h" 21 #include "MCTargetDesc/AArch64AddressingModes.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/CodeGen/CallingConvLower.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineInstrBuilder.h" 26 #include "llvm/CodeGen/MachineRegisterInfo.h" 27 #include "llvm/IR/Function.h" 28 #include "llvm/IR/GetElementPtrTypeIterator.h" 29 #include "llvm/IR/Intrinsics.h" 30 #include "llvm/IR/Type.h" 31 #include "llvm/Support/CommandLine.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/ErrorHandling.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include "llvm/Target/TargetOptions.h" 36 using namespace llvm; 37 38 #define DEBUG_TYPE "aarch64-lower" 39 40 STATISTIC(NumTailCalls, "Number of tail calls"); 41 STATISTIC(NumShiftInserts, "Number of vector shift inserts"); 42 43 static cl::opt<bool> 44 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden, 45 cl::desc("Allow AArch64 SLI/SRI formation"), 46 cl::init(false)); 47 48 // FIXME: The necessary dtprel relocations don't seem to be supported 49 // well in the GNU bfd and gold linkers at the moment. Therefore, by 50 // default, for now, fall back to GeneralDynamic code generation. 51 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration( 52 "aarch64-elf-ldtls-generation", cl::Hidden, 53 cl::desc("Allow AArch64 Local Dynamic TLS code generation"), 54 cl::init(false)); 55 56 /// Value type used for condition codes. 57 static const MVT MVT_CC = MVT::i32; 58 59 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM, 60 const AArch64Subtarget &STI) 61 : TargetLowering(TM), Subtarget(&STI) { 62 63 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so 64 // we have to make something up. Arbitrarily, choose ZeroOrOne. 65 setBooleanContents(ZeroOrOneBooleanContent); 66 // When comparing vectors the result sets the different elements in the 67 // vector to all-one or all-zero. 68 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 69 70 // Set up the register classes. 71 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass); 72 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass); 73 74 if (Subtarget->hasFPARMv8()) { 75 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass); 76 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass); 77 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass); 78 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass); 79 } 80 81 if (Subtarget->hasNEON()) { 82 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass); 83 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass); 84 // Someone set us up the NEON. 85 addDRTypeForNEON(MVT::v2f32); 86 addDRTypeForNEON(MVT::v8i8); 87 addDRTypeForNEON(MVT::v4i16); 88 addDRTypeForNEON(MVT::v2i32); 89 addDRTypeForNEON(MVT::v1i64); 90 addDRTypeForNEON(MVT::v1f64); 91 addDRTypeForNEON(MVT::v4f16); 92 93 addQRTypeForNEON(MVT::v4f32); 94 addQRTypeForNEON(MVT::v2f64); 95 addQRTypeForNEON(MVT::v16i8); 96 addQRTypeForNEON(MVT::v8i16); 97 addQRTypeForNEON(MVT::v4i32); 98 addQRTypeForNEON(MVT::v2i64); 99 addQRTypeForNEON(MVT::v8f16); 100 } 101 102 // Compute derived properties from the register classes 103 computeRegisterProperties(Subtarget->getRegisterInfo()); 104 105 // Provide all sorts of operation actions 106 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 107 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 108 setOperationAction(ISD::SETCC, MVT::i32, Custom); 109 setOperationAction(ISD::SETCC, MVT::i64, Custom); 110 setOperationAction(ISD::SETCC, MVT::f32, Custom); 111 setOperationAction(ISD::SETCC, MVT::f64, Custom); 112 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 113 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 114 setOperationAction(ISD::BR_CC, MVT::i64, Custom); 115 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 116 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 117 setOperationAction(ISD::SELECT, MVT::i32, Custom); 118 setOperationAction(ISD::SELECT, MVT::i64, Custom); 119 setOperationAction(ISD::SELECT, MVT::f32, Custom); 120 setOperationAction(ISD::SELECT, MVT::f64, Custom); 121 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 122 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom); 123 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 124 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 125 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 126 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 127 128 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 129 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 130 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 131 132 setOperationAction(ISD::FREM, MVT::f32, Expand); 133 setOperationAction(ISD::FREM, MVT::f64, Expand); 134 setOperationAction(ISD::FREM, MVT::f80, Expand); 135 136 // Custom lowering hooks are needed for XOR 137 // to fold it into CSINC/CSINV. 138 setOperationAction(ISD::XOR, MVT::i32, Custom); 139 setOperationAction(ISD::XOR, MVT::i64, Custom); 140 141 // Virtually no operation on f128 is legal, but LLVM can't expand them when 142 // there's a valid register class, so we need custom operations in most cases. 143 setOperationAction(ISD::FABS, MVT::f128, Expand); 144 setOperationAction(ISD::FADD, MVT::f128, Custom); 145 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 146 setOperationAction(ISD::FCOS, MVT::f128, Expand); 147 setOperationAction(ISD::FDIV, MVT::f128, Custom); 148 setOperationAction(ISD::FMA, MVT::f128, Expand); 149 setOperationAction(ISD::FMUL, MVT::f128, Custom); 150 setOperationAction(ISD::FNEG, MVT::f128, Expand); 151 setOperationAction(ISD::FPOW, MVT::f128, Expand); 152 setOperationAction(ISD::FREM, MVT::f128, Expand); 153 setOperationAction(ISD::FRINT, MVT::f128, Expand); 154 setOperationAction(ISD::FSIN, MVT::f128, Expand); 155 setOperationAction(ISD::FSINCOS, MVT::f128, Expand); 156 setOperationAction(ISD::FSQRT, MVT::f128, Expand); 157 setOperationAction(ISD::FSUB, MVT::f128, Custom); 158 setOperationAction(ISD::FTRUNC, MVT::f128, Expand); 159 setOperationAction(ISD::SETCC, MVT::f128, Custom); 160 setOperationAction(ISD::BR_CC, MVT::f128, Custom); 161 setOperationAction(ISD::SELECT, MVT::f128, Custom); 162 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); 163 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom); 164 165 // Lowering for many of the conversions is actually specified by the non-f128 166 // type. The LowerXXX function will be trivial when f128 isn't involved. 167 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 168 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 169 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom); 170 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 171 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 172 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom); 173 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 174 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 175 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom); 176 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 177 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 178 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom); 179 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 180 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom); 181 182 // Variable arguments. 183 setOperationAction(ISD::VASTART, MVT::Other, Custom); 184 setOperationAction(ISD::VAARG, MVT::Other, Custom); 185 setOperationAction(ISD::VACOPY, MVT::Other, Custom); 186 setOperationAction(ISD::VAEND, MVT::Other, Expand); 187 188 // Variable-sized objects. 189 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 190 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 191 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand); 192 193 // Constant pool entries 194 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 195 196 // BlockAddress 197 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 198 199 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences. 200 setOperationAction(ISD::ADDC, MVT::i32, Custom); 201 setOperationAction(ISD::ADDE, MVT::i32, Custom); 202 setOperationAction(ISD::SUBC, MVT::i32, Custom); 203 setOperationAction(ISD::SUBE, MVT::i32, Custom); 204 setOperationAction(ISD::ADDC, MVT::i64, Custom); 205 setOperationAction(ISD::ADDE, MVT::i64, Custom); 206 setOperationAction(ISD::SUBC, MVT::i64, Custom); 207 setOperationAction(ISD::SUBE, MVT::i64, Custom); 208 209 // AArch64 lacks both left-rotate and popcount instructions. 210 setOperationAction(ISD::ROTL, MVT::i32, Expand); 211 setOperationAction(ISD::ROTL, MVT::i64, Expand); 212 for (MVT VT : MVT::vector_valuetypes()) { 213 setOperationAction(ISD::ROTL, VT, Expand); 214 setOperationAction(ISD::ROTR, VT, Expand); 215 } 216 217 // AArch64 doesn't have {U|S}MUL_LOHI. 218 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 219 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 220 221 222 setOperationAction(ISD::CTPOP, MVT::i32, Custom); 223 setOperationAction(ISD::CTPOP, MVT::i64, Custom); 224 225 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 226 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 227 for (MVT VT : MVT::vector_valuetypes()) { 228 setOperationAction(ISD::SDIVREM, VT, Expand); 229 setOperationAction(ISD::UDIVREM, VT, Expand); 230 } 231 setOperationAction(ISD::SREM, MVT::i32, Expand); 232 setOperationAction(ISD::SREM, MVT::i64, Expand); 233 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 234 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 235 setOperationAction(ISD::UREM, MVT::i32, Expand); 236 setOperationAction(ISD::UREM, MVT::i64, Expand); 237 238 // Custom lower Add/Sub/Mul with overflow. 239 setOperationAction(ISD::SADDO, MVT::i32, Custom); 240 setOperationAction(ISD::SADDO, MVT::i64, Custom); 241 setOperationAction(ISD::UADDO, MVT::i32, Custom); 242 setOperationAction(ISD::UADDO, MVT::i64, Custom); 243 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 244 setOperationAction(ISD::SSUBO, MVT::i64, Custom); 245 setOperationAction(ISD::USUBO, MVT::i32, Custom); 246 setOperationAction(ISD::USUBO, MVT::i64, Custom); 247 setOperationAction(ISD::SMULO, MVT::i32, Custom); 248 setOperationAction(ISD::SMULO, MVT::i64, Custom); 249 setOperationAction(ISD::UMULO, MVT::i32, Custom); 250 setOperationAction(ISD::UMULO, MVT::i64, Custom); 251 252 setOperationAction(ISD::FSIN, MVT::f32, Expand); 253 setOperationAction(ISD::FSIN, MVT::f64, Expand); 254 setOperationAction(ISD::FCOS, MVT::f32, Expand); 255 setOperationAction(ISD::FCOS, MVT::f64, Expand); 256 setOperationAction(ISD::FPOW, MVT::f32, Expand); 257 setOperationAction(ISD::FPOW, MVT::f64, Expand); 258 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 259 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 260 261 // f16 is a storage-only type, always promote it to f32. 262 setOperationAction(ISD::SETCC, MVT::f16, Promote); 263 setOperationAction(ISD::BR_CC, MVT::f16, Promote); 264 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote); 265 setOperationAction(ISD::SELECT, MVT::f16, Promote); 266 setOperationAction(ISD::FADD, MVT::f16, Promote); 267 setOperationAction(ISD::FSUB, MVT::f16, Promote); 268 setOperationAction(ISD::FMUL, MVT::f16, Promote); 269 setOperationAction(ISD::FDIV, MVT::f16, Promote); 270 setOperationAction(ISD::FREM, MVT::f16, Promote); 271 setOperationAction(ISD::FMA, MVT::f16, Promote); 272 setOperationAction(ISD::FNEG, MVT::f16, Promote); 273 setOperationAction(ISD::FABS, MVT::f16, Promote); 274 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 275 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote); 276 setOperationAction(ISD::FCOS, MVT::f16, Promote); 277 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 278 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 279 setOperationAction(ISD::FPOW, MVT::f16, Promote); 280 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 281 setOperationAction(ISD::FRINT, MVT::f16, Promote); 282 setOperationAction(ISD::FSIN, MVT::f16, Promote); 283 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 284 setOperationAction(ISD::FSQRT, MVT::f16, Promote); 285 setOperationAction(ISD::FEXP, MVT::f16, Promote); 286 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 287 setOperationAction(ISD::FLOG, MVT::f16, Promote); 288 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 289 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 290 setOperationAction(ISD::FROUND, MVT::f16, Promote); 291 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 292 setOperationAction(ISD::FMINNUM, MVT::f16, Promote); 293 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote); 294 setOperationAction(ISD::FMINNAN, MVT::f16, Promote); 295 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote); 296 297 // v4f16 is also a storage-only type, so promote it to v4f32 when that is 298 // known to be safe. 299 setOperationAction(ISD::FADD, MVT::v4f16, Promote); 300 setOperationAction(ISD::FSUB, MVT::v4f16, Promote); 301 setOperationAction(ISD::FMUL, MVT::v4f16, Promote); 302 setOperationAction(ISD::FDIV, MVT::v4f16, Promote); 303 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote); 304 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote); 305 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32); 306 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32); 307 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32); 308 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32); 309 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32); 310 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32); 311 312 // Expand all other v4f16 operations. 313 // FIXME: We could generate better code by promoting some operations to 314 // a pair of v4f32s 315 setOperationAction(ISD::FABS, MVT::v4f16, Expand); 316 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand); 317 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand); 318 setOperationAction(ISD::FCOS, MVT::v4f16, Expand); 319 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand); 320 setOperationAction(ISD::FMA, MVT::v4f16, Expand); 321 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand); 322 setOperationAction(ISD::FNEG, MVT::v4f16, Expand); 323 setOperationAction(ISD::FPOW, MVT::v4f16, Expand); 324 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand); 325 setOperationAction(ISD::FREM, MVT::v4f16, Expand); 326 setOperationAction(ISD::FROUND, MVT::v4f16, Expand); 327 setOperationAction(ISD::FRINT, MVT::v4f16, Expand); 328 setOperationAction(ISD::FSIN, MVT::v4f16, Expand); 329 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand); 330 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand); 331 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand); 332 setOperationAction(ISD::SETCC, MVT::v4f16, Expand); 333 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand); 334 setOperationAction(ISD::SELECT, MVT::v4f16, Expand); 335 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand); 336 setOperationAction(ISD::FEXP, MVT::v4f16, Expand); 337 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand); 338 setOperationAction(ISD::FLOG, MVT::v4f16, Expand); 339 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand); 340 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand); 341 342 343 // v8f16 is also a storage-only type, so expand it. 344 setOperationAction(ISD::FABS, MVT::v8f16, Expand); 345 setOperationAction(ISD::FADD, MVT::v8f16, Expand); 346 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand); 347 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand); 348 setOperationAction(ISD::FCOS, MVT::v8f16, Expand); 349 setOperationAction(ISD::FDIV, MVT::v8f16, Expand); 350 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand); 351 setOperationAction(ISD::FMA, MVT::v8f16, Expand); 352 setOperationAction(ISD::FMUL, MVT::v8f16, Expand); 353 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand); 354 setOperationAction(ISD::FNEG, MVT::v8f16, Expand); 355 setOperationAction(ISD::FPOW, MVT::v8f16, Expand); 356 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand); 357 setOperationAction(ISD::FREM, MVT::v8f16, Expand); 358 setOperationAction(ISD::FROUND, MVT::v8f16, Expand); 359 setOperationAction(ISD::FRINT, MVT::v8f16, Expand); 360 setOperationAction(ISD::FSIN, MVT::v8f16, Expand); 361 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand); 362 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand); 363 setOperationAction(ISD::FSUB, MVT::v8f16, Expand); 364 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand); 365 setOperationAction(ISD::SETCC, MVT::v8f16, Expand); 366 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand); 367 setOperationAction(ISD::SELECT, MVT::v8f16, Expand); 368 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand); 369 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand); 370 setOperationAction(ISD::FEXP, MVT::v8f16, Expand); 371 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand); 372 setOperationAction(ISD::FLOG, MVT::v8f16, Expand); 373 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand); 374 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand); 375 376 // AArch64 has implementations of a lot of rounding-like FP operations. 377 for (MVT Ty : {MVT::f32, MVT::f64}) { 378 setOperationAction(ISD::FFLOOR, Ty, Legal); 379 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 380 setOperationAction(ISD::FCEIL, Ty, Legal); 381 setOperationAction(ISD::FRINT, Ty, Legal); 382 setOperationAction(ISD::FTRUNC, Ty, Legal); 383 setOperationAction(ISD::FROUND, Ty, Legal); 384 setOperationAction(ISD::FMINNUM, Ty, Legal); 385 setOperationAction(ISD::FMAXNUM, Ty, Legal); 386 setOperationAction(ISD::FMINNAN, Ty, Legal); 387 setOperationAction(ISD::FMAXNAN, Ty, Legal); 388 } 389 390 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 391 392 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom); 393 394 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0. 395 // This requires the Performance Monitors extension. 396 if (Subtarget->hasPerfMon()) 397 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 398 399 if (Subtarget->isTargetMachO()) { 400 // For iOS, we don't want to the normal expansion of a libcall to 401 // sincos. We want to issue a libcall to __sincos_stret to avoid memory 402 // traffic. 403 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 404 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 405 } else { 406 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 407 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 408 } 409 410 // Make floating-point constants legal for the large code model, so they don't 411 // become loads from the constant pool. 412 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) { 413 setOperationAction(ISD::ConstantFP, MVT::f32, Legal); 414 setOperationAction(ISD::ConstantFP, MVT::f64, Legal); 415 } 416 417 // AArch64 does not have floating-point extending loads, i1 sign-extending 418 // load, floating-point truncating stores, or v2i32->v2i16 truncating store. 419 for (MVT VT : MVT::fp_valuetypes()) { 420 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 421 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 422 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand); 423 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand); 424 } 425 for (MVT VT : MVT::integer_valuetypes()) 426 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand); 427 428 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 429 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 430 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 431 setTruncStoreAction(MVT::f128, MVT::f80, Expand); 432 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 433 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 434 setTruncStoreAction(MVT::f128, MVT::f16, Expand); 435 436 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 437 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 438 439 // Indexed loads and stores are supported. 440 for (unsigned im = (unsigned)ISD::PRE_INC; 441 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 442 setIndexedLoadAction(im, MVT::i8, Legal); 443 setIndexedLoadAction(im, MVT::i16, Legal); 444 setIndexedLoadAction(im, MVT::i32, Legal); 445 setIndexedLoadAction(im, MVT::i64, Legal); 446 setIndexedLoadAction(im, MVT::f64, Legal); 447 setIndexedLoadAction(im, MVT::f32, Legal); 448 setIndexedLoadAction(im, MVT::f16, Legal); 449 setIndexedStoreAction(im, MVT::i8, Legal); 450 setIndexedStoreAction(im, MVT::i16, Legal); 451 setIndexedStoreAction(im, MVT::i32, Legal); 452 setIndexedStoreAction(im, MVT::i64, Legal); 453 setIndexedStoreAction(im, MVT::f64, Legal); 454 setIndexedStoreAction(im, MVT::f32, Legal); 455 setIndexedStoreAction(im, MVT::f16, Legal); 456 } 457 458 // Trap. 459 setOperationAction(ISD::TRAP, MVT::Other, Legal); 460 461 // We combine OR nodes for bitfield operations. 462 setTargetDAGCombine(ISD::OR); 463 464 // Vector add and sub nodes may conceal a high-half opportunity. 465 // Also, try to fold ADD into CSINC/CSINV.. 466 setTargetDAGCombine(ISD::ADD); 467 setTargetDAGCombine(ISD::SUB); 468 setTargetDAGCombine(ISD::SRL); 469 setTargetDAGCombine(ISD::XOR); 470 setTargetDAGCombine(ISD::SINT_TO_FP); 471 setTargetDAGCombine(ISD::UINT_TO_FP); 472 473 setTargetDAGCombine(ISD::FP_TO_SINT); 474 setTargetDAGCombine(ISD::FP_TO_UINT); 475 setTargetDAGCombine(ISD::FDIV); 476 477 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 478 479 setTargetDAGCombine(ISD::ANY_EXTEND); 480 setTargetDAGCombine(ISD::ZERO_EXTEND); 481 setTargetDAGCombine(ISD::SIGN_EXTEND); 482 setTargetDAGCombine(ISD::BITCAST); 483 setTargetDAGCombine(ISD::CONCAT_VECTORS); 484 setTargetDAGCombine(ISD::STORE); 485 if (Subtarget->supportsAddressTopByteIgnored()) 486 setTargetDAGCombine(ISD::LOAD); 487 488 setTargetDAGCombine(ISD::MUL); 489 490 setTargetDAGCombine(ISD::SELECT); 491 setTargetDAGCombine(ISD::VSELECT); 492 493 setTargetDAGCombine(ISD::INTRINSIC_VOID); 494 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 495 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 496 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT); 497 498 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8; 499 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4; 500 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4; 501 502 setStackPointerRegisterToSaveRestore(AArch64::SP); 503 504 setSchedulingPreference(Sched::Hybrid); 505 506 // Enable TBZ/TBNZ 507 MaskAndBranchFoldingIsLegal = true; 508 EnableExtLdPromotion = true; 509 510 // Set required alignment. 511 setMinFunctionAlignment(2); 512 // Set preferred alignments. 513 setPrefFunctionAlignment(STI.getPrefFunctionAlignment()); 514 setPrefLoopAlignment(STI.getPrefLoopAlignment()); 515 516 // Only change the limit for entries in a jump table if specified by 517 // the subtarget, but not at the command line. 518 unsigned MaxJT = STI.getMaximumJumpTableSize(); 519 if (MaxJT && getMaximumJumpTableSize() == 0) 520 setMaximumJumpTableSize(MaxJT); 521 522 setHasExtractBitsInsn(true); 523 524 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 525 526 if (Subtarget->hasNEON()) { 527 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to 528 // silliness like this: 529 setOperationAction(ISD::FABS, MVT::v1f64, Expand); 530 setOperationAction(ISD::FADD, MVT::v1f64, Expand); 531 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand); 532 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand); 533 setOperationAction(ISD::FCOS, MVT::v1f64, Expand); 534 setOperationAction(ISD::FDIV, MVT::v1f64, Expand); 535 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand); 536 setOperationAction(ISD::FMA, MVT::v1f64, Expand); 537 setOperationAction(ISD::FMUL, MVT::v1f64, Expand); 538 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand); 539 setOperationAction(ISD::FNEG, MVT::v1f64, Expand); 540 setOperationAction(ISD::FPOW, MVT::v1f64, Expand); 541 setOperationAction(ISD::FREM, MVT::v1f64, Expand); 542 setOperationAction(ISD::FROUND, MVT::v1f64, Expand); 543 setOperationAction(ISD::FRINT, MVT::v1f64, Expand); 544 setOperationAction(ISD::FSIN, MVT::v1f64, Expand); 545 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand); 546 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand); 547 setOperationAction(ISD::FSUB, MVT::v1f64, Expand); 548 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand); 549 setOperationAction(ISD::SETCC, MVT::v1f64, Expand); 550 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand); 551 setOperationAction(ISD::SELECT, MVT::v1f64, Expand); 552 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand); 553 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand); 554 555 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand); 556 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand); 557 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand); 558 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand); 559 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand); 560 561 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 562 563 // AArch64 doesn't have a direct vector ->f32 conversion instructions for 564 // elements smaller than i32, so promote the input to i32 first. 565 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote); 566 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote); 567 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote); 568 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote); 569 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16 570 // -> v8f16 conversions. 571 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote); 572 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote); 573 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote); 574 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote); 575 // Similarly, there is no direct i32 -> f64 vector conversion instruction. 576 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom); 577 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom); 578 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom); 579 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom); 580 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the 581 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16 582 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom); 583 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom); 584 585 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 586 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 587 588 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand); 589 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand); 590 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand); 591 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand); 592 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand); 593 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand); 594 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand); 595 setOperationAction(ISD::CTTZ, MVT::v2i64, Expand); 596 597 // AArch64 doesn't have MUL.2d: 598 setOperationAction(ISD::MUL, MVT::v2i64, Expand); 599 // Custom handling for some quad-vector types to detect MULL. 600 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 601 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 602 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 603 604 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal); 605 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 606 // Likewise, narrowing and extending vector loads/stores aren't handled 607 // directly. 608 for (MVT VT : MVT::vector_valuetypes()) { 609 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 610 611 setOperationAction(ISD::MULHS, VT, Expand); 612 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 613 setOperationAction(ISD::MULHU, VT, Expand); 614 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 615 616 setOperationAction(ISD::BSWAP, VT, Expand); 617 618 for (MVT InnerVT : MVT::vector_valuetypes()) { 619 setTruncStoreAction(VT, InnerVT, Expand); 620 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 621 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 622 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 623 } 624 } 625 626 // AArch64 has implementations of a lot of rounding-like FP operations. 627 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) { 628 setOperationAction(ISD::FFLOOR, Ty, Legal); 629 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 630 setOperationAction(ISD::FCEIL, Ty, Legal); 631 setOperationAction(ISD::FRINT, Ty, Legal); 632 setOperationAction(ISD::FTRUNC, Ty, Legal); 633 setOperationAction(ISD::FROUND, Ty, Legal); 634 } 635 } 636 637 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive(); 638 } 639 640 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) { 641 if (VT == MVT::v2f32 || VT == MVT::v4f16) { 642 setOperationAction(ISD::LOAD, VT, Promote); 643 AddPromotedToType(ISD::LOAD, VT, MVT::v2i32); 644 645 setOperationAction(ISD::STORE, VT, Promote); 646 AddPromotedToType(ISD::STORE, VT, MVT::v2i32); 647 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) { 648 setOperationAction(ISD::LOAD, VT, Promote); 649 AddPromotedToType(ISD::LOAD, VT, MVT::v2i64); 650 651 setOperationAction(ISD::STORE, VT, Promote); 652 AddPromotedToType(ISD::STORE, VT, MVT::v2i64); 653 } 654 655 // Mark vector float intrinsics as expand. 656 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) { 657 setOperationAction(ISD::FSIN, VT, Expand); 658 setOperationAction(ISD::FCOS, VT, Expand); 659 setOperationAction(ISD::FPOWI, VT, Expand); 660 setOperationAction(ISD::FPOW, VT, Expand); 661 setOperationAction(ISD::FLOG, VT, Expand); 662 setOperationAction(ISD::FLOG2, VT, Expand); 663 setOperationAction(ISD::FLOG10, VT, Expand); 664 setOperationAction(ISD::FEXP, VT, Expand); 665 setOperationAction(ISD::FEXP2, VT, Expand); 666 667 // But we do support custom-lowering for FCOPYSIGN. 668 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 669 } 670 671 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 672 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 673 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 674 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 675 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 676 setOperationAction(ISD::SRA, VT, Custom); 677 setOperationAction(ISD::SRL, VT, Custom); 678 setOperationAction(ISD::SHL, VT, Custom); 679 setOperationAction(ISD::AND, VT, Custom); 680 setOperationAction(ISD::OR, VT, Custom); 681 setOperationAction(ISD::SETCC, VT, Custom); 682 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 683 684 setOperationAction(ISD::SELECT, VT, Expand); 685 setOperationAction(ISD::SELECT_CC, VT, Expand); 686 setOperationAction(ISD::VSELECT, VT, Expand); 687 for (MVT InnerVT : MVT::all_valuetypes()) 688 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand); 689 690 // CNT supports only B element sizes. 691 if (VT != MVT::v8i8 && VT != MVT::v16i8) 692 setOperationAction(ISD::CTPOP, VT, Expand); 693 694 setOperationAction(ISD::UDIV, VT, Expand); 695 setOperationAction(ISD::SDIV, VT, Expand); 696 setOperationAction(ISD::UREM, VT, Expand); 697 setOperationAction(ISD::SREM, VT, Expand); 698 setOperationAction(ISD::FREM, VT, Expand); 699 700 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 701 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 702 703 // [SU][MIN|MAX] are available for all NEON types apart from i64. 704 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64) 705 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 706 setOperationAction(Opcode, VT, Legal); 707 708 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!). 709 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16) 710 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN, 711 ISD::FMINNUM, ISD::FMAXNUM}) 712 setOperationAction(Opcode, VT, Legal); 713 714 if (Subtarget->isLittleEndian()) { 715 for (unsigned im = (unsigned)ISD::PRE_INC; 716 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 717 setIndexedLoadAction(im, VT, Legal); 718 setIndexedStoreAction(im, VT, Legal); 719 } 720 } 721 } 722 723 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) { 724 addRegisterClass(VT, &AArch64::FPR64RegClass); 725 addTypeForNEON(VT, MVT::v2i32); 726 } 727 728 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) { 729 addRegisterClass(VT, &AArch64::FPR128RegClass); 730 addTypeForNEON(VT, MVT::v4i32); 731 } 732 733 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &, 734 EVT VT) const { 735 if (!VT.isVector()) 736 return MVT::i32; 737 return VT.changeVectorElementTypeToInteger(); 738 } 739 740 /// computeKnownBitsForTargetNode - Determine which of the bits specified in 741 /// Mask are known to be either zero or one and return them in the 742 /// KnownZero/KnownOne bitsets. 743 void AArch64TargetLowering::computeKnownBitsForTargetNode( 744 const SDValue Op, APInt &KnownZero, APInt &KnownOne, 745 const SelectionDAG &DAG, unsigned Depth) const { 746 switch (Op.getOpcode()) { 747 default: 748 break; 749 case AArch64ISD::CSEL: { 750 APInt KnownZero2, KnownOne2; 751 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1); 752 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1); 753 KnownZero &= KnownZero2; 754 KnownOne &= KnownOne2; 755 break; 756 } 757 case ISD::INTRINSIC_W_CHAIN: { 758 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 759 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 760 switch (IntID) { 761 default: return; 762 case Intrinsic::aarch64_ldaxr: 763 case Intrinsic::aarch64_ldxr: { 764 unsigned BitWidth = KnownOne.getBitWidth(); 765 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 766 unsigned MemBits = VT.getScalarSizeInBits(); 767 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 768 return; 769 } 770 } 771 break; 772 } 773 case ISD::INTRINSIC_WO_CHAIN: 774 case ISD::INTRINSIC_VOID: { 775 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 776 switch (IntNo) { 777 default: 778 break; 779 case Intrinsic::aarch64_neon_umaxv: 780 case Intrinsic::aarch64_neon_uminv: { 781 // Figure out the datatype of the vector operand. The UMINV instruction 782 // will zero extend the result, so we can mark as known zero all the 783 // bits larger than the element datatype. 32-bit or larget doesn't need 784 // this as those are legal types and will be handled by isel directly. 785 MVT VT = Op.getOperand(1).getValueType().getSimpleVT(); 786 unsigned BitWidth = KnownZero.getBitWidth(); 787 if (VT == MVT::v8i8 || VT == MVT::v16i8) { 788 assert(BitWidth >= 8 && "Unexpected width!"); 789 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8); 790 KnownZero |= Mask; 791 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) { 792 assert(BitWidth >= 16 && "Unexpected width!"); 793 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16); 794 KnownZero |= Mask; 795 } 796 break; 797 } break; 798 } 799 } 800 } 801 } 802 803 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL, 804 EVT) const { 805 return MVT::i64; 806 } 807 808 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT, 809 unsigned AddrSpace, 810 unsigned Align, 811 bool *Fast) const { 812 if (Subtarget->requiresStrictAlign()) 813 return false; 814 815 if (Fast) { 816 // Some CPUs are fine with unaligned stores except for 128-bit ones. 817 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 || 818 // See comments in performSTORECombine() for more details about 819 // these conditions. 820 821 // Code that uses clang vector extensions can mark that it 822 // wants unaligned accesses to be treated as fast by 823 // underspecifying alignment to be 1 or 2. 824 Align <= 2 || 825 826 // Disregard v2i64. Memcpy lowering produces those and splitting 827 // them regresses performance on micro-benchmarks and olden/bh. 828 VT == MVT::v2i64; 829 } 830 return true; 831 } 832 833 FastISel * 834 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 835 const TargetLibraryInfo *libInfo) const { 836 return AArch64::createFastISel(funcInfo, libInfo); 837 } 838 839 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const { 840 switch ((AArch64ISD::NodeType)Opcode) { 841 case AArch64ISD::FIRST_NUMBER: break; 842 case AArch64ISD::CALL: return "AArch64ISD::CALL"; 843 case AArch64ISD::ADRP: return "AArch64ISD::ADRP"; 844 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow"; 845 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot"; 846 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG"; 847 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND"; 848 case AArch64ISD::CSEL: return "AArch64ISD::CSEL"; 849 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL"; 850 case AArch64ISD::CSINV: return "AArch64ISD::CSINV"; 851 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG"; 852 case AArch64ISD::CSINC: return "AArch64ISD::CSINC"; 853 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER"; 854 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ"; 855 case AArch64ISD::ADC: return "AArch64ISD::ADC"; 856 case AArch64ISD::SBC: return "AArch64ISD::SBC"; 857 case AArch64ISD::ADDS: return "AArch64ISD::ADDS"; 858 case AArch64ISD::SUBS: return "AArch64ISD::SUBS"; 859 case AArch64ISD::ADCS: return "AArch64ISD::ADCS"; 860 case AArch64ISD::SBCS: return "AArch64ISD::SBCS"; 861 case AArch64ISD::ANDS: return "AArch64ISD::ANDS"; 862 case AArch64ISD::CCMP: return "AArch64ISD::CCMP"; 863 case AArch64ISD::CCMN: return "AArch64ISD::CCMN"; 864 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP"; 865 case AArch64ISD::FCMP: return "AArch64ISD::FCMP"; 866 case AArch64ISD::DUP: return "AArch64ISD::DUP"; 867 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8"; 868 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16"; 869 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32"; 870 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64"; 871 case AArch64ISD::MOVI: return "AArch64ISD::MOVI"; 872 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift"; 873 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit"; 874 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl"; 875 case AArch64ISD::FMOV: return "AArch64ISD::FMOV"; 876 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift"; 877 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl"; 878 case AArch64ISD::BICi: return "AArch64ISD::BICi"; 879 case AArch64ISD::ORRi: return "AArch64ISD::ORRi"; 880 case AArch64ISD::BSL: return "AArch64ISD::BSL"; 881 case AArch64ISD::NEG: return "AArch64ISD::NEG"; 882 case AArch64ISD::EXTR: return "AArch64ISD::EXTR"; 883 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1"; 884 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2"; 885 case AArch64ISD::UZP1: return "AArch64ISD::UZP1"; 886 case AArch64ISD::UZP2: return "AArch64ISD::UZP2"; 887 case AArch64ISD::TRN1: return "AArch64ISD::TRN1"; 888 case AArch64ISD::TRN2: return "AArch64ISD::TRN2"; 889 case AArch64ISD::REV16: return "AArch64ISD::REV16"; 890 case AArch64ISD::REV32: return "AArch64ISD::REV32"; 891 case AArch64ISD::REV64: return "AArch64ISD::REV64"; 892 case AArch64ISD::EXT: return "AArch64ISD::EXT"; 893 case AArch64ISD::VSHL: return "AArch64ISD::VSHL"; 894 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR"; 895 case AArch64ISD::VASHR: return "AArch64ISD::VASHR"; 896 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ"; 897 case AArch64ISD::CMGE: return "AArch64ISD::CMGE"; 898 case AArch64ISD::CMGT: return "AArch64ISD::CMGT"; 899 case AArch64ISD::CMHI: return "AArch64ISD::CMHI"; 900 case AArch64ISD::CMHS: return "AArch64ISD::CMHS"; 901 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ"; 902 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE"; 903 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT"; 904 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz"; 905 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz"; 906 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz"; 907 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz"; 908 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz"; 909 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz"; 910 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz"; 911 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz"; 912 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz"; 913 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz"; 914 case AArch64ISD::SADDV: return "AArch64ISD::SADDV"; 915 case AArch64ISD::UADDV: return "AArch64ISD::UADDV"; 916 case AArch64ISD::SMINV: return "AArch64ISD::SMINV"; 917 case AArch64ISD::UMINV: return "AArch64ISD::UMINV"; 918 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV"; 919 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV"; 920 case AArch64ISD::NOT: return "AArch64ISD::NOT"; 921 case AArch64ISD::BIT: return "AArch64ISD::BIT"; 922 case AArch64ISD::CBZ: return "AArch64ISD::CBZ"; 923 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ"; 924 case AArch64ISD::TBZ: return "AArch64ISD::TBZ"; 925 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ"; 926 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN"; 927 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH"; 928 case AArch64ISD::SITOF: return "AArch64ISD::SITOF"; 929 case AArch64ISD::UITOF: return "AArch64ISD::UITOF"; 930 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST"; 931 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I"; 932 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I"; 933 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I"; 934 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I"; 935 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I"; 936 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge"; 937 case AArch64ISD::LD2post: return "AArch64ISD::LD2post"; 938 case AArch64ISD::LD3post: return "AArch64ISD::LD3post"; 939 case AArch64ISD::LD4post: return "AArch64ISD::LD4post"; 940 case AArch64ISD::ST2post: return "AArch64ISD::ST2post"; 941 case AArch64ISD::ST3post: return "AArch64ISD::ST3post"; 942 case AArch64ISD::ST4post: return "AArch64ISD::ST4post"; 943 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post"; 944 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post"; 945 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post"; 946 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post"; 947 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post"; 948 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post"; 949 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost"; 950 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost"; 951 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost"; 952 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost"; 953 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost"; 954 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost"; 955 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost"; 956 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost"; 957 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost"; 958 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost"; 959 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost"; 960 case AArch64ISD::SMULL: return "AArch64ISD::SMULL"; 961 case AArch64ISD::UMULL: return "AArch64ISD::UMULL"; 962 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE"; 963 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS"; 964 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE"; 965 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS"; 966 } 967 return nullptr; 968 } 969 970 MachineBasicBlock * 971 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI, 972 MachineBasicBlock *MBB) const { 973 // We materialise the F128CSEL pseudo-instruction as some control flow and a 974 // phi node: 975 976 // OrigBB: 977 // [... previous instrs leading to comparison ...] 978 // b.ne TrueBB 979 // b EndBB 980 // TrueBB: 981 // ; Fallthrough 982 // EndBB: 983 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB] 984 985 MachineFunction *MF = MBB->getParent(); 986 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 987 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 988 DebugLoc DL = MI.getDebugLoc(); 989 MachineFunction::iterator It = ++MBB->getIterator(); 990 991 unsigned DestReg = MI.getOperand(0).getReg(); 992 unsigned IfTrueReg = MI.getOperand(1).getReg(); 993 unsigned IfFalseReg = MI.getOperand(2).getReg(); 994 unsigned CondCode = MI.getOperand(3).getImm(); 995 bool NZCVKilled = MI.getOperand(4).isKill(); 996 997 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB); 998 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB); 999 MF->insert(It, TrueBB); 1000 MF->insert(It, EndBB); 1001 1002 // Transfer rest of current basic-block to EndBB 1003 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)), 1004 MBB->end()); 1005 EndBB->transferSuccessorsAndUpdatePHIs(MBB); 1006 1007 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB); 1008 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB); 1009 MBB->addSuccessor(TrueBB); 1010 MBB->addSuccessor(EndBB); 1011 1012 // TrueBB falls through to the end. 1013 TrueBB->addSuccessor(EndBB); 1014 1015 if (!NZCVKilled) { 1016 TrueBB->addLiveIn(AArch64::NZCV); 1017 EndBB->addLiveIn(AArch64::NZCV); 1018 } 1019 1020 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg) 1021 .addReg(IfTrueReg) 1022 .addMBB(TrueBB) 1023 .addReg(IfFalseReg) 1024 .addMBB(MBB); 1025 1026 MI.eraseFromParent(); 1027 return EndBB; 1028 } 1029 1030 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter( 1031 MachineInstr &MI, MachineBasicBlock *BB) const { 1032 switch (MI.getOpcode()) { 1033 default: 1034 #ifndef NDEBUG 1035 MI.dump(); 1036 #endif 1037 llvm_unreachable("Unexpected instruction for custom inserter!"); 1038 1039 case AArch64::F128CSEL: 1040 return EmitF128CSEL(MI, BB); 1041 1042 case TargetOpcode::STACKMAP: 1043 case TargetOpcode::PATCHPOINT: 1044 return emitPatchPoint(MI, BB); 1045 } 1046 } 1047 1048 //===----------------------------------------------------------------------===// 1049 // AArch64 Lowering private implementation. 1050 //===----------------------------------------------------------------------===// 1051 1052 //===----------------------------------------------------------------------===// 1053 // Lowering Code 1054 //===----------------------------------------------------------------------===// 1055 1056 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64 1057 /// CC 1058 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) { 1059 switch (CC) { 1060 default: 1061 llvm_unreachable("Unknown condition code!"); 1062 case ISD::SETNE: 1063 return AArch64CC::NE; 1064 case ISD::SETEQ: 1065 return AArch64CC::EQ; 1066 case ISD::SETGT: 1067 return AArch64CC::GT; 1068 case ISD::SETGE: 1069 return AArch64CC::GE; 1070 case ISD::SETLT: 1071 return AArch64CC::LT; 1072 case ISD::SETLE: 1073 return AArch64CC::LE; 1074 case ISD::SETUGT: 1075 return AArch64CC::HI; 1076 case ISD::SETUGE: 1077 return AArch64CC::HS; 1078 case ISD::SETULT: 1079 return AArch64CC::LO; 1080 case ISD::SETULE: 1081 return AArch64CC::LS; 1082 } 1083 } 1084 1085 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC. 1086 static void changeFPCCToAArch64CC(ISD::CondCode CC, 1087 AArch64CC::CondCode &CondCode, 1088 AArch64CC::CondCode &CondCode2) { 1089 CondCode2 = AArch64CC::AL; 1090 switch (CC) { 1091 default: 1092 llvm_unreachable("Unknown FP condition!"); 1093 case ISD::SETEQ: 1094 case ISD::SETOEQ: 1095 CondCode = AArch64CC::EQ; 1096 break; 1097 case ISD::SETGT: 1098 case ISD::SETOGT: 1099 CondCode = AArch64CC::GT; 1100 break; 1101 case ISD::SETGE: 1102 case ISD::SETOGE: 1103 CondCode = AArch64CC::GE; 1104 break; 1105 case ISD::SETOLT: 1106 CondCode = AArch64CC::MI; 1107 break; 1108 case ISD::SETOLE: 1109 CondCode = AArch64CC::LS; 1110 break; 1111 case ISD::SETONE: 1112 CondCode = AArch64CC::MI; 1113 CondCode2 = AArch64CC::GT; 1114 break; 1115 case ISD::SETO: 1116 CondCode = AArch64CC::VC; 1117 break; 1118 case ISD::SETUO: 1119 CondCode = AArch64CC::VS; 1120 break; 1121 case ISD::SETUEQ: 1122 CondCode = AArch64CC::EQ; 1123 CondCode2 = AArch64CC::VS; 1124 break; 1125 case ISD::SETUGT: 1126 CondCode = AArch64CC::HI; 1127 break; 1128 case ISD::SETUGE: 1129 CondCode = AArch64CC::PL; 1130 break; 1131 case ISD::SETLT: 1132 case ISD::SETULT: 1133 CondCode = AArch64CC::LT; 1134 break; 1135 case ISD::SETLE: 1136 case ISD::SETULE: 1137 CondCode = AArch64CC::LE; 1138 break; 1139 case ISD::SETNE: 1140 case ISD::SETUNE: 1141 CondCode = AArch64CC::NE; 1142 break; 1143 } 1144 } 1145 1146 /// Convert a DAG fp condition code to an AArch64 CC. 1147 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that 1148 /// should be AND'ed instead of OR'ed. 1149 static void changeFPCCToANDAArch64CC(ISD::CondCode CC, 1150 AArch64CC::CondCode &CondCode, 1151 AArch64CC::CondCode &CondCode2) { 1152 CondCode2 = AArch64CC::AL; 1153 switch (CC) { 1154 default: 1155 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 1156 assert(CondCode2 == AArch64CC::AL); 1157 break; 1158 case ISD::SETONE: 1159 // (a one b) 1160 // == ((a olt b) || (a ogt b)) 1161 // == ((a ord b) && (a une b)) 1162 CondCode = AArch64CC::VC; 1163 CondCode2 = AArch64CC::NE; 1164 break; 1165 case ISD::SETUEQ: 1166 // (a ueq b) 1167 // == ((a uno b) || (a oeq b)) 1168 // == ((a ule b) && (a uge b)) 1169 CondCode = AArch64CC::PL; 1170 CondCode2 = AArch64CC::LE; 1171 break; 1172 } 1173 } 1174 1175 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 1176 /// CC usable with the vector instructions. Fewer operations are available 1177 /// without a real NZCV register, so we have to use less efficient combinations 1178 /// to get the same effect. 1179 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC, 1180 AArch64CC::CondCode &CondCode, 1181 AArch64CC::CondCode &CondCode2, 1182 bool &Invert) { 1183 Invert = false; 1184 switch (CC) { 1185 default: 1186 // Mostly the scalar mappings work fine. 1187 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 1188 break; 1189 case ISD::SETUO: 1190 Invert = true; 1191 LLVM_FALLTHROUGH; 1192 case ISD::SETO: 1193 CondCode = AArch64CC::MI; 1194 CondCode2 = AArch64CC::GE; 1195 break; 1196 case ISD::SETUEQ: 1197 case ISD::SETULT: 1198 case ISD::SETULE: 1199 case ISD::SETUGT: 1200 case ISD::SETUGE: 1201 // All of the compare-mask comparisons are ordered, but we can switch 1202 // between the two by a double inversion. E.g. ULE == !OGT. 1203 Invert = true; 1204 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2); 1205 break; 1206 } 1207 } 1208 1209 static bool isLegalArithImmed(uint64_t C) { 1210 // Matches AArch64DAGToDAGISel::SelectArithImmed(). 1211 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0); 1212 } 1213 1214 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC, 1215 const SDLoc &dl, SelectionDAG &DAG) { 1216 EVT VT = LHS.getValueType(); 1217 1218 if (VT.isFloatingPoint()) { 1219 assert(VT != MVT::f128); 1220 if (VT == MVT::f16) { 1221 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 1222 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 1223 VT = MVT::f32; 1224 } 1225 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS); 1226 } 1227 1228 // The CMP instruction is just an alias for SUBS, and representing it as 1229 // SUBS means that it's possible to get CSE with subtract operations. 1230 // A later phase can perform the optimization of setting the destination 1231 // register to WZR/XZR if it ends up being unused. 1232 unsigned Opcode = AArch64ISD::SUBS; 1233 1234 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) && 1235 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 1236 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on 1237 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags 1238 // can be set differently by this operation. It comes down to whether 1239 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then 1240 // everything is fine. If not then the optimization is wrong. Thus general 1241 // comparisons are only valid if op2 != 0. 1242 1243 // So, finally, the only LLVM-native comparisons that don't mention C and V 1244 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in 1245 // the absence of information about op2. 1246 Opcode = AArch64ISD::ADDS; 1247 RHS = RHS.getOperand(1); 1248 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) && 1249 !isUnsignedIntSetCC(CC)) { 1250 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST 1251 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one 1252 // of the signed comparisons. 1253 Opcode = AArch64ISD::ANDS; 1254 RHS = LHS.getOperand(1); 1255 LHS = LHS.getOperand(0); 1256 } 1257 1258 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS) 1259 .getValue(1); 1260 } 1261 1262 /// \defgroup AArch64CCMP CMP;CCMP matching 1263 /// 1264 /// These functions deal with the formation of CMP;CCMP;... sequences. 1265 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of 1266 /// a comparison. They set the NZCV flags to a predefined value if their 1267 /// predicate is false. This allows to express arbitrary conjunctions, for 1268 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))" 1269 /// expressed as: 1270 /// cmp A 1271 /// ccmp B, inv(CB), CA 1272 /// check for CB flags 1273 /// 1274 /// In general we can create code for arbitrary "... (and (and A B) C)" 1275 /// sequences. We can also implement some "or" expressions, because "(or A B)" 1276 /// is equivalent to "not (and (not A) (not B))" and we can implement some 1277 /// negation operations: 1278 /// We can negate the results of a single comparison by inverting the flags 1279 /// used when the predicate fails and inverting the flags tested in the next 1280 /// instruction; We can also negate the results of the whole previous 1281 /// conditional compare sequence by inverting the flags tested in the next 1282 /// instruction. However there is no way to negate the result of a partial 1283 /// sequence. 1284 /// 1285 /// Therefore on encountering an "or" expression we can negate the subtree on 1286 /// one side and have to be able to push the negate to the leafs of the subtree 1287 /// on the other side (see also the comments in code). As complete example: 1288 /// "or (or (setCA (cmp A)) (setCB (cmp B))) 1289 /// (and (setCC (cmp C)) (setCD (cmp D)))" 1290 /// is transformed to 1291 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D)))) 1292 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))" 1293 /// and implemented as: 1294 /// cmp C 1295 /// ccmp D, inv(CD), CC 1296 /// ccmp A, CA, inv(CD) 1297 /// ccmp B, CB, inv(CA) 1298 /// check for CB flags 1299 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented 1300 /// by conditional compare sequences. 1301 /// @{ 1302 1303 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate. 1304 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS, 1305 ISD::CondCode CC, SDValue CCOp, 1306 AArch64CC::CondCode Predicate, 1307 AArch64CC::CondCode OutCC, 1308 const SDLoc &DL, SelectionDAG &DAG) { 1309 unsigned Opcode = 0; 1310 if (LHS.getValueType().isFloatingPoint()) { 1311 assert(LHS.getValueType() != MVT::f128); 1312 if (LHS.getValueType() == MVT::f16) { 1313 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS); 1314 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS); 1315 } 1316 Opcode = AArch64ISD::FCCMP; 1317 } else if (RHS.getOpcode() == ISD::SUB) { 1318 SDValue SubOp0 = RHS.getOperand(0); 1319 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 1320 // See emitComparison() on why we can only do this for SETEQ and SETNE. 1321 Opcode = AArch64ISD::CCMN; 1322 RHS = RHS.getOperand(1); 1323 } 1324 } 1325 if (Opcode == 0) 1326 Opcode = AArch64ISD::CCMP; 1327 1328 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC); 1329 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC); 1330 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC); 1331 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32); 1332 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp); 1333 } 1334 1335 /// Returns true if @p Val is a tree of AND/OR/SETCC operations. 1336 /// CanPushNegate is set to true if we can push a negate operation through 1337 /// the tree in a was that we are left with AND operations and negate operations 1338 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to 1339 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be 1340 /// brought into such a form. 1341 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate, 1342 unsigned Depth = 0) { 1343 if (!Val.hasOneUse()) 1344 return false; 1345 unsigned Opcode = Val->getOpcode(); 1346 if (Opcode == ISD::SETCC) { 1347 if (Val->getOperand(0).getValueType() == MVT::f128) 1348 return false; 1349 CanNegate = true; 1350 return true; 1351 } 1352 // Protect against exponential runtime and stack overflow. 1353 if (Depth > 6) 1354 return false; 1355 if (Opcode == ISD::AND || Opcode == ISD::OR) { 1356 SDValue O0 = Val->getOperand(0); 1357 SDValue O1 = Val->getOperand(1); 1358 bool CanNegateL; 1359 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1)) 1360 return false; 1361 bool CanNegateR; 1362 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1)) 1363 return false; 1364 1365 if (Opcode == ISD::OR) { 1366 // For an OR expression we need to be able to negate at least one side or 1367 // we cannot do the transformation at all. 1368 if (!CanNegateL && !CanNegateR) 1369 return false; 1370 // We can however change a (not (or x y)) to (and (not x) (not y)) if we 1371 // can negate the x and y subtrees. 1372 CanNegate = CanNegateL && CanNegateR; 1373 } else { 1374 // If the operands are OR expressions then we finally need to negate their 1375 // outputs, we can only do that for the operand with emitted last by 1376 // negating OutCC, not for both operands. 1377 bool NeedsNegOutL = O0->getOpcode() == ISD::OR; 1378 bool NeedsNegOutR = O1->getOpcode() == ISD::OR; 1379 if (NeedsNegOutL && NeedsNegOutR) 1380 return false; 1381 // We cannot negate an AND operation (it would become an OR), 1382 CanNegate = false; 1383 } 1384 return true; 1385 } 1386 return false; 1387 } 1388 1389 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain 1390 /// of CCMP/CFCMP ops. See @ref AArch64CCMP. 1391 /// Tries to transform the given i1 producing node @p Val to a series compare 1392 /// and conditional compare operations. @returns an NZCV flags producing node 1393 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if 1394 /// transformation was not possible. 1395 /// On recursive invocations @p PushNegate may be set to true to have negation 1396 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate 1397 /// for the comparisons in the current subtree; @p Depth limits the search 1398 /// depth to avoid stack overflow. 1399 static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val, 1400 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp, 1401 AArch64CC::CondCode Predicate) { 1402 // We're at a tree leaf, produce a conditional comparison operation. 1403 unsigned Opcode = Val->getOpcode(); 1404 if (Opcode == ISD::SETCC) { 1405 SDValue LHS = Val->getOperand(0); 1406 SDValue RHS = Val->getOperand(1); 1407 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get(); 1408 bool isInteger = LHS.getValueType().isInteger(); 1409 if (Negate) 1410 CC = getSetCCInverse(CC, isInteger); 1411 SDLoc DL(Val); 1412 // Determine OutCC and handle FP special case. 1413 if (isInteger) { 1414 OutCC = changeIntCCToAArch64CC(CC); 1415 } else { 1416 assert(LHS.getValueType().isFloatingPoint()); 1417 AArch64CC::CondCode ExtraCC; 1418 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC); 1419 // Some floating point conditions can't be tested with a single condition 1420 // code. Construct an additional comparison in this case. 1421 if (ExtraCC != AArch64CC::AL) { 1422 SDValue ExtraCmp; 1423 if (!CCOp.getNode()) 1424 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG); 1425 else 1426 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, 1427 ExtraCC, DL, DAG); 1428 CCOp = ExtraCmp; 1429 Predicate = ExtraCC; 1430 } 1431 } 1432 1433 // Produce a normal comparison if we are first in the chain 1434 if (!CCOp) 1435 return emitComparison(LHS, RHS, CC, DL, DAG); 1436 // Otherwise produce a ccmp. 1437 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL, 1438 DAG); 1439 } 1440 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) && 1441 "Valid conjunction/disjunction tree"); 1442 1443 // Check if both sides can be transformed. 1444 SDValue LHS = Val->getOperand(0); 1445 SDValue RHS = Val->getOperand(1); 1446 1447 // In case of an OR we need to negate our operands and the result. 1448 // (A v B) <=> not(not(A) ^ not(B)) 1449 bool NegateOpsAndResult = Opcode == ISD::OR; 1450 // We can negate the results of all previous operations by inverting the 1451 // predicate flags giving us a free negation for one side. The other side 1452 // must be negatable by itself. 1453 if (NegateOpsAndResult) { 1454 // See which side we can negate. 1455 bool CanNegateL; 1456 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL); 1457 assert(isValidL && "Valid conjunction/disjunction tree"); 1458 (void)isValidL; 1459 1460 #ifndef NDEBUG 1461 bool CanNegateR; 1462 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR); 1463 assert(isValidR && "Valid conjunction/disjunction tree"); 1464 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree"); 1465 #endif 1466 1467 // Order the side which we cannot negate to RHS so we can emit it first. 1468 if (!CanNegateL) 1469 std::swap(LHS, RHS); 1470 } else { 1471 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR; 1472 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) && 1473 "Valid conjunction/disjunction tree"); 1474 // Order the side where we need to negate the output flags to RHS so it 1475 // gets emitted first. 1476 if (NeedsNegOutL) 1477 std::swap(LHS, RHS); 1478 } 1479 1480 // Emit RHS. If we want to negate the tree we only need to push a negate 1481 // through if we are already in a PushNegate case, otherwise we can negate 1482 // the "flags to test" afterwards. 1483 AArch64CC::CondCode RHSCC; 1484 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate, 1485 CCOp, Predicate); 1486 if (NegateOpsAndResult && !Negate) 1487 RHSCC = AArch64CC::getInvertedCondCode(RHSCC); 1488 // Emit LHS. We may need to negate it. 1489 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC, 1490 NegateOpsAndResult, CmpR, 1491 RHSCC); 1492 // If we transformed an OR to and AND then we have to negate the result 1493 // (or absorb the Negate parameter). 1494 if (NegateOpsAndResult && !Negate) 1495 OutCC = AArch64CC::getInvertedCondCode(OutCC); 1496 return CmpL; 1497 } 1498 1499 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain 1500 /// of CCMP/CFCMP ops. See @ref AArch64CCMP. 1501 /// \see emitConjunctionDisjunctionTreeRec(). 1502 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val, 1503 AArch64CC::CondCode &OutCC) { 1504 bool CanNegate; 1505 if (!isConjunctionDisjunctionTree(Val, CanNegate)) 1506 return SDValue(); 1507 1508 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(), 1509 AArch64CC::AL); 1510 } 1511 1512 /// @} 1513 1514 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 1515 SDValue &AArch64cc, SelectionDAG &DAG, 1516 const SDLoc &dl) { 1517 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 1518 EVT VT = RHS.getValueType(); 1519 uint64_t C = RHSC->getZExtValue(); 1520 if (!isLegalArithImmed(C)) { 1521 // Constant does not fit, try adjusting it by one? 1522 switch (CC) { 1523 default: 1524 break; 1525 case ISD::SETLT: 1526 case ISD::SETGE: 1527 if ((VT == MVT::i32 && C != 0x80000000 && 1528 isLegalArithImmed((uint32_t)(C - 1))) || 1529 (VT == MVT::i64 && C != 0x80000000ULL && 1530 isLegalArithImmed(C - 1ULL))) { 1531 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 1532 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 1533 RHS = DAG.getConstant(C, dl, VT); 1534 } 1535 break; 1536 case ISD::SETULT: 1537 case ISD::SETUGE: 1538 if ((VT == MVT::i32 && C != 0 && 1539 isLegalArithImmed((uint32_t)(C - 1))) || 1540 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) { 1541 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 1542 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 1543 RHS = DAG.getConstant(C, dl, VT); 1544 } 1545 break; 1546 case ISD::SETLE: 1547 case ISD::SETGT: 1548 if ((VT == MVT::i32 && C != INT32_MAX && 1549 isLegalArithImmed((uint32_t)(C + 1))) || 1550 (VT == MVT::i64 && C != INT64_MAX && 1551 isLegalArithImmed(C + 1ULL))) { 1552 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 1553 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 1554 RHS = DAG.getConstant(C, dl, VT); 1555 } 1556 break; 1557 case ISD::SETULE: 1558 case ISD::SETUGT: 1559 if ((VT == MVT::i32 && C != UINT32_MAX && 1560 isLegalArithImmed((uint32_t)(C + 1))) || 1561 (VT == MVT::i64 && C != UINT64_MAX && 1562 isLegalArithImmed(C + 1ULL))) { 1563 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 1564 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 1565 RHS = DAG.getConstant(C, dl, VT); 1566 } 1567 break; 1568 } 1569 } 1570 } 1571 SDValue Cmp; 1572 AArch64CC::CondCode AArch64CC; 1573 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) { 1574 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS); 1575 1576 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095. 1577 // For the i8 operand, the largest immediate is 255, so this can be easily 1578 // encoded in the compare instruction. For the i16 operand, however, the 1579 // largest immediate cannot be encoded in the compare. 1580 // Therefore, use a sign extending load and cmn to avoid materializing the 1581 // -1 constant. For example, 1582 // movz w1, #65535 1583 // ldrh w0, [x0, #0] 1584 // cmp w0, w1 1585 // > 1586 // ldrsh w0, [x0, #0] 1587 // cmn w0, #1 1588 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS) 1589 // if and only if (sext LHS) == (sext RHS). The checks are in place to 1590 // ensure both the LHS and RHS are truly zero extended and to make sure the 1591 // transformation is profitable. 1592 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) && 1593 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD && 1594 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 && 1595 LHS.getNode()->hasNUsesOfValue(1, 0)) { 1596 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue(); 1597 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) { 1598 SDValue SExt = 1599 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS, 1600 DAG.getValueType(MVT::i16)); 1601 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl, 1602 RHS.getValueType()), 1603 CC, dl, DAG); 1604 AArch64CC = changeIntCCToAArch64CC(CC); 1605 } 1606 } 1607 1608 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) { 1609 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) { 1610 if ((CC == ISD::SETNE) ^ RHSC->isNullValue()) 1611 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC); 1612 } 1613 } 1614 } 1615 1616 if (!Cmp) { 1617 Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 1618 AArch64CC = changeIntCCToAArch64CC(CC); 1619 } 1620 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC); 1621 return Cmp; 1622 } 1623 1624 static std::pair<SDValue, SDValue> 1625 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) { 1626 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) && 1627 "Unsupported value type"); 1628 SDValue Value, Overflow; 1629 SDLoc DL(Op); 1630 SDValue LHS = Op.getOperand(0); 1631 SDValue RHS = Op.getOperand(1); 1632 unsigned Opc = 0; 1633 switch (Op.getOpcode()) { 1634 default: 1635 llvm_unreachable("Unknown overflow instruction!"); 1636 case ISD::SADDO: 1637 Opc = AArch64ISD::ADDS; 1638 CC = AArch64CC::VS; 1639 break; 1640 case ISD::UADDO: 1641 Opc = AArch64ISD::ADDS; 1642 CC = AArch64CC::HS; 1643 break; 1644 case ISD::SSUBO: 1645 Opc = AArch64ISD::SUBS; 1646 CC = AArch64CC::VS; 1647 break; 1648 case ISD::USUBO: 1649 Opc = AArch64ISD::SUBS; 1650 CC = AArch64CC::LO; 1651 break; 1652 // Multiply needs a little bit extra work. 1653 case ISD::SMULO: 1654 case ISD::UMULO: { 1655 CC = AArch64CC::NE; 1656 bool IsSigned = Op.getOpcode() == ISD::SMULO; 1657 if (Op.getValueType() == MVT::i32) { 1658 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 1659 // For a 32 bit multiply with overflow check we want the instruction 1660 // selector to generate a widening multiply (SMADDL/UMADDL). For that we 1661 // need to generate the following pattern: 1662 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b)) 1663 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS); 1664 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS); 1665 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 1666 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul, 1667 DAG.getConstant(0, DL, MVT::i64)); 1668 // On AArch64 the upper 32 bits are always zero extended for a 32 bit 1669 // operation. We need to clear out the upper 32 bits, because we used a 1670 // widening multiply that wrote all 64 bits. In the end this should be a 1671 // noop. 1672 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add); 1673 if (IsSigned) { 1674 // The signed overflow check requires more than just a simple check for 1675 // any bit set in the upper 32 bits of the result. These bits could be 1676 // just the sign bits of a negative number. To perform the overflow 1677 // check we have to arithmetic shift right the 32nd bit of the result by 1678 // 31 bits. Then we compare the result to the upper 32 bits. 1679 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add, 1680 DAG.getConstant(32, DL, MVT::i64)); 1681 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits); 1682 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value, 1683 DAG.getConstant(31, DL, MVT::i64)); 1684 // It is important that LowerBits is last, otherwise the arithmetic 1685 // shift will not be folded into the compare (SUBS). 1686 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32); 1687 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 1688 .getValue(1); 1689 } else { 1690 // The overflow check for unsigned multiply is easy. We only need to 1691 // check if any of the upper 32 bits are set. This can be done with a 1692 // CMP (shifted register). For that we need to generate the following 1693 // pattern: 1694 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32) 1695 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul, 1696 DAG.getConstant(32, DL, MVT::i64)); 1697 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 1698 Overflow = 1699 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 1700 DAG.getConstant(0, DL, MVT::i64), 1701 UpperBits).getValue(1); 1702 } 1703 break; 1704 } 1705 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type"); 1706 // For the 64 bit multiply 1707 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 1708 if (IsSigned) { 1709 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS); 1710 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value, 1711 DAG.getConstant(63, DL, MVT::i64)); 1712 // It is important that LowerBits is last, otherwise the arithmetic 1713 // shift will not be folded into the compare (SUBS). 1714 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 1715 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 1716 .getValue(1); 1717 } else { 1718 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS); 1719 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 1720 Overflow = 1721 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 1722 DAG.getConstant(0, DL, MVT::i64), 1723 UpperBits).getValue(1); 1724 } 1725 break; 1726 } 1727 } // switch (...) 1728 1729 if (Opc) { 1730 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32); 1731 1732 // Emit the AArch64 operation with overflow check. 1733 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS); 1734 Overflow = Value.getValue(1); 1735 } 1736 return std::make_pair(Value, Overflow); 1737 } 1738 1739 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG, 1740 RTLIB::Libcall Call) const { 1741 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end()); 1742 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first; 1743 } 1744 1745 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) { 1746 SDValue Sel = Op.getOperand(0); 1747 SDValue Other = Op.getOperand(1); 1748 1749 // If neither operand is a SELECT_CC, give up. 1750 if (Sel.getOpcode() != ISD::SELECT_CC) 1751 std::swap(Sel, Other); 1752 if (Sel.getOpcode() != ISD::SELECT_CC) 1753 return Op; 1754 1755 // The folding we want to perform is: 1756 // (xor x, (select_cc a, b, cc, 0, -1) ) 1757 // --> 1758 // (csel x, (xor x, -1), cc ...) 1759 // 1760 // The latter will get matched to a CSINV instruction. 1761 1762 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get(); 1763 SDValue LHS = Sel.getOperand(0); 1764 SDValue RHS = Sel.getOperand(1); 1765 SDValue TVal = Sel.getOperand(2); 1766 SDValue FVal = Sel.getOperand(3); 1767 SDLoc dl(Sel); 1768 1769 // FIXME: This could be generalized to non-integer comparisons. 1770 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 1771 return Op; 1772 1773 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 1774 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 1775 1776 // The values aren't constants, this isn't the pattern we're looking for. 1777 if (!CFVal || !CTVal) 1778 return Op; 1779 1780 // We can commute the SELECT_CC by inverting the condition. This 1781 // might be needed to make this fit into a CSINV pattern. 1782 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) { 1783 std::swap(TVal, FVal); 1784 std::swap(CTVal, CFVal); 1785 CC = ISD::getSetCCInverse(CC, true); 1786 } 1787 1788 // If the constants line up, perform the transform! 1789 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) { 1790 SDValue CCVal; 1791 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 1792 1793 FVal = Other; 1794 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other, 1795 DAG.getConstant(-1ULL, dl, Other.getValueType())); 1796 1797 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal, 1798 CCVal, Cmp); 1799 } 1800 1801 return Op; 1802 } 1803 1804 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 1805 EVT VT = Op.getValueType(); 1806 1807 // Let legalize expand this if it isn't a legal type yet. 1808 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 1809 return SDValue(); 1810 1811 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 1812 1813 unsigned Opc; 1814 bool ExtraOp = false; 1815 switch (Op.getOpcode()) { 1816 default: 1817 llvm_unreachable("Invalid code"); 1818 case ISD::ADDC: 1819 Opc = AArch64ISD::ADDS; 1820 break; 1821 case ISD::SUBC: 1822 Opc = AArch64ISD::SUBS; 1823 break; 1824 case ISD::ADDE: 1825 Opc = AArch64ISD::ADCS; 1826 ExtraOp = true; 1827 break; 1828 case ISD::SUBE: 1829 Opc = AArch64ISD::SBCS; 1830 ExtraOp = true; 1831 break; 1832 } 1833 1834 if (!ExtraOp) 1835 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1)); 1836 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1), 1837 Op.getOperand(2)); 1838 } 1839 1840 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) { 1841 // Let legalize expand this if it isn't a legal type yet. 1842 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 1843 return SDValue(); 1844 1845 SDLoc dl(Op); 1846 AArch64CC::CondCode CC; 1847 // The actual operation that sets the overflow or carry flag. 1848 SDValue Value, Overflow; 1849 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG); 1850 1851 // We use 0 and 1 as false and true values. 1852 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 1853 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 1854 1855 // We use an inverted condition, because the conditional select is inverted 1856 // too. This will allow it to be selected to a single instruction: 1857 // CSINC Wd, WZR, WZR, invert(cond). 1858 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); 1859 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal, 1860 CCVal, Overflow); 1861 1862 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 1863 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 1864 } 1865 1866 // Prefetch operands are: 1867 // 1: Address to prefetch 1868 // 2: bool isWrite 1869 // 3: int locality (0 = no locality ... 3 = extreme locality) 1870 // 4: bool isDataCache 1871 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) { 1872 SDLoc DL(Op); 1873 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 1874 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 1875 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 1876 1877 bool IsStream = !Locality; 1878 // When the locality number is set 1879 if (Locality) { 1880 // The front-end should have filtered out the out-of-range values 1881 assert(Locality <= 3 && "Prefetch locality out-of-range"); 1882 // The locality degree is the opposite of the cache speed. 1883 // Put the number the other way around. 1884 // The encoding starts at 0 for level 1 1885 Locality = 3 - Locality; 1886 } 1887 1888 // built the mask value encoding the expected behavior. 1889 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit 1890 (!IsData << 3) | // IsDataCache bit 1891 (Locality << 1) | // Cache level bits 1892 (unsigned)IsStream; // Stream bit 1893 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0), 1894 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1)); 1895 } 1896 1897 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op, 1898 SelectionDAG &DAG) const { 1899 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering"); 1900 1901 RTLIB::Libcall LC; 1902 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 1903 1904 return LowerF128Call(Op, DAG, LC); 1905 } 1906 1907 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op, 1908 SelectionDAG &DAG) const { 1909 if (Op.getOperand(0).getValueType() != MVT::f128) { 1910 // It's legal except when f128 is involved 1911 return Op; 1912 } 1913 1914 RTLIB::Libcall LC; 1915 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 1916 1917 // FP_ROUND node has a second operand indicating whether it is known to be 1918 // precise. That doesn't take part in the LibCall so we can't directly use 1919 // LowerF128Call. 1920 SDValue SrcVal = Op.getOperand(0); 1921 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 1922 SDLoc(Op)).first; 1923 } 1924 1925 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) { 1926 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 1927 // Any additional optimization in this function should be recorded 1928 // in the cost tables. 1929 EVT InVT = Op.getOperand(0).getValueType(); 1930 EVT VT = Op.getValueType(); 1931 unsigned NumElts = InVT.getVectorNumElements(); 1932 1933 // f16 vectors are promoted to f32 before a conversion. 1934 if (InVT.getVectorElementType() == MVT::f16) { 1935 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts); 1936 SDLoc dl(Op); 1937 return DAG.getNode( 1938 Op.getOpcode(), dl, Op.getValueType(), 1939 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0))); 1940 } 1941 1942 if (VT.getSizeInBits() < InVT.getSizeInBits()) { 1943 SDLoc dl(Op); 1944 SDValue Cv = 1945 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(), 1946 Op.getOperand(0)); 1947 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv); 1948 } 1949 1950 if (VT.getSizeInBits() > InVT.getSizeInBits()) { 1951 SDLoc dl(Op); 1952 MVT ExtVT = 1953 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()), 1954 VT.getVectorNumElements()); 1955 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0)); 1956 return DAG.getNode(Op.getOpcode(), dl, VT, Ext); 1957 } 1958 1959 // Type changing conversions are illegal. 1960 return Op; 1961 } 1962 1963 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op, 1964 SelectionDAG &DAG) const { 1965 if (Op.getOperand(0).getValueType().isVector()) 1966 return LowerVectorFP_TO_INT(Op, DAG); 1967 1968 // f16 conversions are promoted to f32. 1969 if (Op.getOperand(0).getValueType() == MVT::f16) { 1970 SDLoc dl(Op); 1971 return DAG.getNode( 1972 Op.getOpcode(), dl, Op.getValueType(), 1973 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0))); 1974 } 1975 1976 if (Op.getOperand(0).getValueType() != MVT::f128) { 1977 // It's legal except when f128 is involved 1978 return Op; 1979 } 1980 1981 RTLIB::Libcall LC; 1982 if (Op.getOpcode() == ISD::FP_TO_SINT) 1983 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType()); 1984 else 1985 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType()); 1986 1987 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end()); 1988 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first; 1989 } 1990 1991 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 1992 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 1993 // Any additional optimization in this function should be recorded 1994 // in the cost tables. 1995 EVT VT = Op.getValueType(); 1996 SDLoc dl(Op); 1997 SDValue In = Op.getOperand(0); 1998 EVT InVT = In.getValueType(); 1999 2000 if (VT.getSizeInBits() < InVT.getSizeInBits()) { 2001 MVT CastVT = 2002 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()), 2003 InVT.getVectorNumElements()); 2004 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In); 2005 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl)); 2006 } 2007 2008 if (VT.getSizeInBits() > InVT.getSizeInBits()) { 2009 unsigned CastOpc = 2010 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 2011 EVT CastVT = VT.changeVectorElementTypeToInteger(); 2012 In = DAG.getNode(CastOpc, dl, CastVT, In); 2013 return DAG.getNode(Op.getOpcode(), dl, VT, In); 2014 } 2015 2016 return Op; 2017 } 2018 2019 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op, 2020 SelectionDAG &DAG) const { 2021 if (Op.getValueType().isVector()) 2022 return LowerVectorINT_TO_FP(Op, DAG); 2023 2024 // f16 conversions are promoted to f32. 2025 if (Op.getValueType() == MVT::f16) { 2026 SDLoc dl(Op); 2027 return DAG.getNode( 2028 ISD::FP_ROUND, dl, MVT::f16, 2029 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)), 2030 DAG.getIntPtrConstant(0, dl)); 2031 } 2032 2033 // i128 conversions are libcalls. 2034 if (Op.getOperand(0).getValueType() == MVT::i128) 2035 return SDValue(); 2036 2037 // Other conversions are legal, unless it's to the completely software-based 2038 // fp128. 2039 if (Op.getValueType() != MVT::f128) 2040 return Op; 2041 2042 RTLIB::Libcall LC; 2043 if (Op.getOpcode() == ISD::SINT_TO_FP) 2044 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType()); 2045 else 2046 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType()); 2047 2048 return LowerF128Call(Op, DAG, LC); 2049 } 2050 2051 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op, 2052 SelectionDAG &DAG) const { 2053 // For iOS, we want to call an alternative entry point: __sincos_stret, 2054 // which returns the values in two S / D registers. 2055 SDLoc dl(Op); 2056 SDValue Arg = Op.getOperand(0); 2057 EVT ArgVT = Arg.getValueType(); 2058 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 2059 2060 ArgListTy Args; 2061 ArgListEntry Entry; 2062 2063 Entry.Node = Arg; 2064 Entry.Ty = ArgTy; 2065 Entry.isSExt = false; 2066 Entry.isZExt = false; 2067 Args.push_back(Entry); 2068 2069 const char *LibcallName = 2070 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret"; 2071 SDValue Callee = 2072 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout())); 2073 2074 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr); 2075 TargetLowering::CallLoweringInfo CLI(DAG); 2076 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode()) 2077 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args)); 2078 2079 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2080 return CallResult.first; 2081 } 2082 2083 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) { 2084 if (Op.getValueType() != MVT::f16) 2085 return SDValue(); 2086 2087 assert(Op.getOperand(0).getValueType() == MVT::i16); 2088 SDLoc DL(Op); 2089 2090 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0)); 2091 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op); 2092 return SDValue( 2093 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op, 2094 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 2095 0); 2096 } 2097 2098 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 2099 if (OrigVT.getSizeInBits() >= 64) 2100 return OrigVT; 2101 2102 assert(OrigVT.isSimple() && "Expecting a simple value type"); 2103 2104 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 2105 switch (OrigSimpleTy) { 2106 default: llvm_unreachable("Unexpected Vector Type"); 2107 case MVT::v2i8: 2108 case MVT::v2i16: 2109 return MVT::v2i32; 2110 case MVT::v4i8: 2111 return MVT::v4i16; 2112 } 2113 } 2114 2115 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG, 2116 const EVT &OrigTy, 2117 const EVT &ExtTy, 2118 unsigned ExtOpcode) { 2119 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 2120 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 2121 // 64-bits we need to insert a new extension so that it will be 64-bits. 2122 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 2123 if (OrigTy.getSizeInBits() >= 64) 2124 return N; 2125 2126 // Must extend size to at least 64 bits to be used as an operand for VMULL. 2127 EVT NewVT = getExtensionTo64Bits(OrigTy); 2128 2129 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 2130 } 2131 2132 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 2133 bool isSigned) { 2134 EVT VT = N->getValueType(0); 2135 2136 if (N->getOpcode() != ISD::BUILD_VECTOR) 2137 return false; 2138 2139 for (const SDValue &Elt : N->op_values()) { 2140 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 2141 unsigned EltSize = VT.getScalarSizeInBits(); 2142 unsigned HalfSize = EltSize / 2; 2143 if (isSigned) { 2144 if (!isIntN(HalfSize, C->getSExtValue())) 2145 return false; 2146 } else { 2147 if (!isUIntN(HalfSize, C->getZExtValue())) 2148 return false; 2149 } 2150 continue; 2151 } 2152 return false; 2153 } 2154 2155 return true; 2156 } 2157 2158 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) { 2159 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 2160 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG, 2161 N->getOperand(0)->getValueType(0), 2162 N->getValueType(0), 2163 N->getOpcode()); 2164 2165 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 2166 EVT VT = N->getValueType(0); 2167 SDLoc dl(N); 2168 unsigned EltSize = VT.getScalarSizeInBits() / 2; 2169 unsigned NumElts = VT.getVectorNumElements(); 2170 MVT TruncVT = MVT::getIntegerVT(EltSize); 2171 SmallVector<SDValue, 8> Ops; 2172 for (unsigned i = 0; i != NumElts; ++i) { 2173 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 2174 const APInt &CInt = C->getAPIntValue(); 2175 // Element types smaller than 32 bits are not legal, so use i32 elements. 2176 // The values are implicitly truncated so sext vs. zext doesn't matter. 2177 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 2178 } 2179 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 2180 } 2181 2182 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 2183 if (N->getOpcode() == ISD::SIGN_EXTEND) 2184 return true; 2185 if (isExtendedBUILD_VECTOR(N, DAG, true)) 2186 return true; 2187 return false; 2188 } 2189 2190 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 2191 if (N->getOpcode() == ISD::ZERO_EXTEND) 2192 return true; 2193 if (isExtendedBUILD_VECTOR(N, DAG, false)) 2194 return true; 2195 return false; 2196 } 2197 2198 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 2199 unsigned Opcode = N->getOpcode(); 2200 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 2201 SDNode *N0 = N->getOperand(0).getNode(); 2202 SDNode *N1 = N->getOperand(1).getNode(); 2203 return N0->hasOneUse() && N1->hasOneUse() && 2204 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 2205 } 2206 return false; 2207 } 2208 2209 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 2210 unsigned Opcode = N->getOpcode(); 2211 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 2212 SDNode *N0 = N->getOperand(0).getNode(); 2213 SDNode *N1 = N->getOperand(1).getNode(); 2214 return N0->hasOneUse() && N1->hasOneUse() && 2215 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 2216 } 2217 return false; 2218 } 2219 2220 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 2221 // Multiplications are only custom-lowered for 128-bit vectors so that 2222 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 2223 EVT VT = Op.getValueType(); 2224 assert(VT.is128BitVector() && VT.isInteger() && 2225 "unexpected type for custom-lowering ISD::MUL"); 2226 SDNode *N0 = Op.getOperand(0).getNode(); 2227 SDNode *N1 = Op.getOperand(1).getNode(); 2228 unsigned NewOpc = 0; 2229 bool isMLA = false; 2230 bool isN0SExt = isSignExtended(N0, DAG); 2231 bool isN1SExt = isSignExtended(N1, DAG); 2232 if (isN0SExt && isN1SExt) 2233 NewOpc = AArch64ISD::SMULL; 2234 else { 2235 bool isN0ZExt = isZeroExtended(N0, DAG); 2236 bool isN1ZExt = isZeroExtended(N1, DAG); 2237 if (isN0ZExt && isN1ZExt) 2238 NewOpc = AArch64ISD::UMULL; 2239 else if (isN1SExt || isN1ZExt) { 2240 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 2241 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 2242 if (isN1SExt && isAddSubSExt(N0, DAG)) { 2243 NewOpc = AArch64ISD::SMULL; 2244 isMLA = true; 2245 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 2246 NewOpc = AArch64ISD::UMULL; 2247 isMLA = true; 2248 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 2249 std::swap(N0, N1); 2250 NewOpc = AArch64ISD::UMULL; 2251 isMLA = true; 2252 } 2253 } 2254 2255 if (!NewOpc) { 2256 if (VT == MVT::v2i64) 2257 // Fall through to expand this. It is not legal. 2258 return SDValue(); 2259 else 2260 // Other vector multiplications are legal. 2261 return Op; 2262 } 2263 } 2264 2265 // Legalize to a S/UMULL instruction 2266 SDLoc DL(Op); 2267 SDValue Op0; 2268 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG); 2269 if (!isMLA) { 2270 Op0 = skipExtensionForVectorMULL(N0, DAG); 2271 assert(Op0.getValueType().is64BitVector() && 2272 Op1.getValueType().is64BitVector() && 2273 "unexpected types for extended operands to VMULL"); 2274 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 2275 } 2276 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during 2277 // isel lowering to take advantage of no-stall back to back s/umul + s/umla. 2278 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57 2279 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG); 2280 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG); 2281 EVT Op1VT = Op1.getValueType(); 2282 return DAG.getNode(N0->getOpcode(), DL, VT, 2283 DAG.getNode(NewOpc, DL, VT, 2284 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 2285 DAG.getNode(NewOpc, DL, VT, 2286 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 2287 } 2288 2289 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 2290 SelectionDAG &DAG) const { 2291 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2292 SDLoc dl(Op); 2293 switch (IntNo) { 2294 default: return SDValue(); // Don't custom lower most intrinsics. 2295 case Intrinsic::thread_pointer: { 2296 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2297 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT); 2298 } 2299 case Intrinsic::aarch64_neon_smax: 2300 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(), 2301 Op.getOperand(1), Op.getOperand(2)); 2302 case Intrinsic::aarch64_neon_umax: 2303 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(), 2304 Op.getOperand(1), Op.getOperand(2)); 2305 case Intrinsic::aarch64_neon_smin: 2306 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(), 2307 Op.getOperand(1), Op.getOperand(2)); 2308 case Intrinsic::aarch64_neon_umin: 2309 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(), 2310 Op.getOperand(1), Op.getOperand(2)); 2311 } 2312 } 2313 2314 SDValue AArch64TargetLowering::LowerOperation(SDValue Op, 2315 SelectionDAG &DAG) const { 2316 switch (Op.getOpcode()) { 2317 default: 2318 llvm_unreachable("unimplemented operand"); 2319 return SDValue(); 2320 case ISD::BITCAST: 2321 return LowerBITCAST(Op, DAG); 2322 case ISD::GlobalAddress: 2323 return LowerGlobalAddress(Op, DAG); 2324 case ISD::GlobalTLSAddress: 2325 return LowerGlobalTLSAddress(Op, DAG); 2326 case ISD::SETCC: 2327 return LowerSETCC(Op, DAG); 2328 case ISD::BR_CC: 2329 return LowerBR_CC(Op, DAG); 2330 case ISD::SELECT: 2331 return LowerSELECT(Op, DAG); 2332 case ISD::SELECT_CC: 2333 return LowerSELECT_CC(Op, DAG); 2334 case ISD::JumpTable: 2335 return LowerJumpTable(Op, DAG); 2336 case ISD::ConstantPool: 2337 return LowerConstantPool(Op, DAG); 2338 case ISD::BlockAddress: 2339 return LowerBlockAddress(Op, DAG); 2340 case ISD::VASTART: 2341 return LowerVASTART(Op, DAG); 2342 case ISD::VACOPY: 2343 return LowerVACOPY(Op, DAG); 2344 case ISD::VAARG: 2345 return LowerVAARG(Op, DAG); 2346 case ISD::ADDC: 2347 case ISD::ADDE: 2348 case ISD::SUBC: 2349 case ISD::SUBE: 2350 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 2351 case ISD::SADDO: 2352 case ISD::UADDO: 2353 case ISD::SSUBO: 2354 case ISD::USUBO: 2355 case ISD::SMULO: 2356 case ISD::UMULO: 2357 return LowerXALUO(Op, DAG); 2358 case ISD::FADD: 2359 return LowerF128Call(Op, DAG, RTLIB::ADD_F128); 2360 case ISD::FSUB: 2361 return LowerF128Call(Op, DAG, RTLIB::SUB_F128); 2362 case ISD::FMUL: 2363 return LowerF128Call(Op, DAG, RTLIB::MUL_F128); 2364 case ISD::FDIV: 2365 return LowerF128Call(Op, DAG, RTLIB::DIV_F128); 2366 case ISD::FP_ROUND: 2367 return LowerFP_ROUND(Op, DAG); 2368 case ISD::FP_EXTEND: 2369 return LowerFP_EXTEND(Op, DAG); 2370 case ISD::FRAMEADDR: 2371 return LowerFRAMEADDR(Op, DAG); 2372 case ISD::RETURNADDR: 2373 return LowerRETURNADDR(Op, DAG); 2374 case ISD::INSERT_VECTOR_ELT: 2375 return LowerINSERT_VECTOR_ELT(Op, DAG); 2376 case ISD::EXTRACT_VECTOR_ELT: 2377 return LowerEXTRACT_VECTOR_ELT(Op, DAG); 2378 case ISD::BUILD_VECTOR: 2379 return LowerBUILD_VECTOR(Op, DAG); 2380 case ISD::VECTOR_SHUFFLE: 2381 return LowerVECTOR_SHUFFLE(Op, DAG); 2382 case ISD::EXTRACT_SUBVECTOR: 2383 return LowerEXTRACT_SUBVECTOR(Op, DAG); 2384 case ISD::SRA: 2385 case ISD::SRL: 2386 case ISD::SHL: 2387 return LowerVectorSRA_SRL_SHL(Op, DAG); 2388 case ISD::SHL_PARTS: 2389 return LowerShiftLeftParts(Op, DAG); 2390 case ISD::SRL_PARTS: 2391 case ISD::SRA_PARTS: 2392 return LowerShiftRightParts(Op, DAG); 2393 case ISD::CTPOP: 2394 return LowerCTPOP(Op, DAG); 2395 case ISD::FCOPYSIGN: 2396 return LowerFCOPYSIGN(Op, DAG); 2397 case ISD::AND: 2398 return LowerVectorAND(Op, DAG); 2399 case ISD::OR: 2400 return LowerVectorOR(Op, DAG); 2401 case ISD::XOR: 2402 return LowerXOR(Op, DAG); 2403 case ISD::PREFETCH: 2404 return LowerPREFETCH(Op, DAG); 2405 case ISD::SINT_TO_FP: 2406 case ISD::UINT_TO_FP: 2407 return LowerINT_TO_FP(Op, DAG); 2408 case ISD::FP_TO_SINT: 2409 case ISD::FP_TO_UINT: 2410 return LowerFP_TO_INT(Op, DAG); 2411 case ISD::FSINCOS: 2412 return LowerFSINCOS(Op, DAG); 2413 case ISD::MUL: 2414 return LowerMUL(Op, DAG); 2415 case ISD::INTRINSIC_WO_CHAIN: 2416 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2417 } 2418 } 2419 2420 //===----------------------------------------------------------------------===// 2421 // Calling Convention Implementation 2422 //===----------------------------------------------------------------------===// 2423 2424 #include "AArch64GenCallingConv.inc" 2425 2426 /// Selects the correct CCAssignFn for a given CallingConvention value. 2427 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC, 2428 bool IsVarArg) const { 2429 switch (CC) { 2430 default: 2431 llvm_unreachable("Unsupported calling convention."); 2432 case CallingConv::WebKit_JS: 2433 return CC_AArch64_WebKit_JS; 2434 case CallingConv::GHC: 2435 return CC_AArch64_GHC; 2436 case CallingConv::C: 2437 case CallingConv::Fast: 2438 case CallingConv::PreserveMost: 2439 case CallingConv::CXX_FAST_TLS: 2440 case CallingConv::Swift: 2441 if (!Subtarget->isTargetDarwin()) 2442 return CC_AArch64_AAPCS; 2443 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS; 2444 } 2445 } 2446 2447 CCAssignFn * 2448 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const { 2449 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS 2450 : RetCC_AArch64_AAPCS; 2451 } 2452 2453 SDValue AArch64TargetLowering::LowerFormalArguments( 2454 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 2455 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2456 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 2457 MachineFunction &MF = DAG.getMachineFunction(); 2458 MachineFrameInfo &MFI = MF.getFrameInfo(); 2459 2460 // Assign locations to all of the incoming arguments. 2461 SmallVector<CCValAssign, 16> ArgLocs; 2462 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 2463 *DAG.getContext()); 2464 2465 // At this point, Ins[].VT may already be promoted to i32. To correctly 2466 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 2467 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 2468 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here 2469 // we use a special version of AnalyzeFormalArguments to pass in ValVT and 2470 // LocVT. 2471 unsigned NumArgs = Ins.size(); 2472 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin(); 2473 unsigned CurArgIdx = 0; 2474 for (unsigned i = 0; i != NumArgs; ++i) { 2475 MVT ValVT = Ins[i].VT; 2476 if (Ins[i].isOrigArg()) { 2477 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx); 2478 CurArgIdx = Ins[i].getOrigArgIndex(); 2479 2480 // Get type of the original argument. 2481 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(), 2482 /*AllowUnknown*/ true); 2483 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other; 2484 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 2485 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 2486 ValVT = MVT::i8; 2487 else if (ActualMVT == MVT::i16) 2488 ValVT = MVT::i16; 2489 } 2490 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 2491 bool Res = 2492 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo); 2493 assert(!Res && "Call operand has unhandled type"); 2494 (void)Res; 2495 } 2496 assert(ArgLocs.size() == Ins.size()); 2497 SmallVector<SDValue, 16> ArgValues; 2498 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 2499 CCValAssign &VA = ArgLocs[i]; 2500 2501 if (Ins[i].Flags.isByVal()) { 2502 // Byval is used for HFAs in the PCS, but the system should work in a 2503 // non-compliant manner for larger structs. 2504 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2505 int Size = Ins[i].Flags.getByValSize(); 2506 unsigned NumRegs = (Size + 7) / 8; 2507 2508 // FIXME: This works on big-endian for composite byvals, which are the common 2509 // case. It should also work for fundamental types too. 2510 unsigned FrameIdx = 2511 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false); 2512 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT); 2513 InVals.push_back(FrameIdxN); 2514 2515 continue; 2516 } 2517 2518 if (VA.isRegLoc()) { 2519 // Arguments stored in registers. 2520 EVT RegVT = VA.getLocVT(); 2521 2522 SDValue ArgValue; 2523 const TargetRegisterClass *RC; 2524 2525 if (RegVT == MVT::i32) 2526 RC = &AArch64::GPR32RegClass; 2527 else if (RegVT == MVT::i64) 2528 RC = &AArch64::GPR64RegClass; 2529 else if (RegVT == MVT::f16) 2530 RC = &AArch64::FPR16RegClass; 2531 else if (RegVT == MVT::f32) 2532 RC = &AArch64::FPR32RegClass; 2533 else if (RegVT == MVT::f64 || RegVT.is64BitVector()) 2534 RC = &AArch64::FPR64RegClass; 2535 else if (RegVT == MVT::f128 || RegVT.is128BitVector()) 2536 RC = &AArch64::FPR128RegClass; 2537 else 2538 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 2539 2540 // Transform the arguments in physical registers into virtual ones. 2541 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 2542 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT); 2543 2544 // If this is an 8, 16 or 32-bit value, it is really passed promoted 2545 // to 64 bits. Insert an assert[sz]ext to capture this, then 2546 // truncate to the right size. 2547 switch (VA.getLocInfo()) { 2548 default: 2549 llvm_unreachable("Unknown loc info!"); 2550 case CCValAssign::Full: 2551 break; 2552 case CCValAssign::BCvt: 2553 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue); 2554 break; 2555 case CCValAssign::AExt: 2556 case CCValAssign::SExt: 2557 case CCValAssign::ZExt: 2558 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt 2559 // nodes after our lowering. 2560 assert(RegVT == Ins[i].VT && "incorrect register location selected"); 2561 break; 2562 } 2563 2564 InVals.push_back(ArgValue); 2565 2566 } else { // VA.isRegLoc() 2567 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem"); 2568 unsigned ArgOffset = VA.getLocMemOffset(); 2569 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8; 2570 2571 uint32_t BEAlign = 0; 2572 if (!Subtarget->isLittleEndian() && ArgSize < 8 && 2573 !Ins[i].Flags.isInConsecutiveRegs()) 2574 BEAlign = 8 - ArgSize; 2575 2576 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true); 2577 2578 // Create load nodes to retrieve arguments from the stack. 2579 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 2580 SDValue ArgValue; 2581 2582 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 2583 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 2584 MVT MemVT = VA.getValVT(); 2585 2586 switch (VA.getLocInfo()) { 2587 default: 2588 break; 2589 case CCValAssign::BCvt: 2590 MemVT = VA.getLocVT(); 2591 break; 2592 case CCValAssign::SExt: 2593 ExtType = ISD::SEXTLOAD; 2594 break; 2595 case CCValAssign::ZExt: 2596 ExtType = ISD::ZEXTLOAD; 2597 break; 2598 case CCValAssign::AExt: 2599 ExtType = ISD::EXTLOAD; 2600 break; 2601 } 2602 2603 ArgValue = DAG.getExtLoad( 2604 ExtType, DL, VA.getLocVT(), Chain, FIN, 2605 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 2606 MemVT); 2607 2608 InVals.push_back(ArgValue); 2609 } 2610 } 2611 2612 // varargs 2613 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 2614 if (isVarArg) { 2615 if (!Subtarget->isTargetDarwin()) { 2616 // The AAPCS variadic function ABI is identical to the non-variadic 2617 // one. As a result there may be more arguments in registers and we should 2618 // save them for future reference. 2619 saveVarArgRegisters(CCInfo, DAG, DL, Chain); 2620 } 2621 2622 // This will point to the next argument passed via stack. 2623 unsigned StackOffset = CCInfo.getNextStackOffset(); 2624 // We currently pass all varargs at 8-byte alignment. 2625 StackOffset = ((StackOffset + 7) & ~7); 2626 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true)); 2627 } 2628 2629 unsigned StackArgSize = CCInfo.getNextStackOffset(); 2630 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2631 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) { 2632 // This is a non-standard ABI so by fiat I say we're allowed to make full 2633 // use of the stack area to be popped, which must be aligned to 16 bytes in 2634 // any case: 2635 StackArgSize = alignTo(StackArgSize, 16); 2636 2637 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding 2638 // a multiple of 16. 2639 FuncInfo->setArgumentStackToRestore(StackArgSize); 2640 2641 // This realignment carries over to the available bytes below. Our own 2642 // callers will guarantee the space is free by giving an aligned value to 2643 // CALLSEQ_START. 2644 } 2645 // Even if we're not expected to free up the space, it's useful to know how 2646 // much is there while considering tail calls (because we can reuse it). 2647 FuncInfo->setBytesInStackArgArea(StackArgSize); 2648 2649 return Chain; 2650 } 2651 2652 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo, 2653 SelectionDAG &DAG, 2654 const SDLoc &DL, 2655 SDValue &Chain) const { 2656 MachineFunction &MF = DAG.getMachineFunction(); 2657 MachineFrameInfo &MFI = MF.getFrameInfo(); 2658 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 2659 auto PtrVT = getPointerTy(DAG.getDataLayout()); 2660 2661 SmallVector<SDValue, 8> MemOps; 2662 2663 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2, 2664 AArch64::X3, AArch64::X4, AArch64::X5, 2665 AArch64::X6, AArch64::X7 }; 2666 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs); 2667 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs); 2668 2669 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR); 2670 int GPRIdx = 0; 2671 if (GPRSaveSize != 0) { 2672 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false); 2673 2674 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT); 2675 2676 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) { 2677 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass); 2678 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64); 2679 SDValue Store = DAG.getStore( 2680 Val.getValue(1), DL, Val, FIN, 2681 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8)); 2682 MemOps.push_back(Store); 2683 FIN = 2684 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT)); 2685 } 2686 } 2687 FuncInfo->setVarArgsGPRIndex(GPRIdx); 2688 FuncInfo->setVarArgsGPRSize(GPRSaveSize); 2689 2690 if (Subtarget->hasFPARMv8()) { 2691 static const MCPhysReg FPRArgRegs[] = { 2692 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, 2693 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7}; 2694 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs); 2695 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs); 2696 2697 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR); 2698 int FPRIdx = 0; 2699 if (FPRSaveSize != 0) { 2700 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false); 2701 2702 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT); 2703 2704 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) { 2705 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass); 2706 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128); 2707 2708 SDValue Store = DAG.getStore( 2709 Val.getValue(1), DL, Val, FIN, 2710 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16)); 2711 MemOps.push_back(Store); 2712 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, 2713 DAG.getConstant(16, DL, PtrVT)); 2714 } 2715 } 2716 FuncInfo->setVarArgsFPRIndex(FPRIdx); 2717 FuncInfo->setVarArgsFPRSize(FPRSaveSize); 2718 } 2719 2720 if (!MemOps.empty()) { 2721 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 2722 } 2723 } 2724 2725 /// LowerCallResult - Lower the result values of a call into the 2726 /// appropriate copies out of appropriate physical registers. 2727 SDValue AArch64TargetLowering::LowerCallResult( 2728 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 2729 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 2730 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 2731 SDValue ThisVal) const { 2732 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 2733 ? RetCC_AArch64_WebKit_JS 2734 : RetCC_AArch64_AAPCS; 2735 // Assign locations to each value returned by this call. 2736 SmallVector<CCValAssign, 16> RVLocs; 2737 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 2738 *DAG.getContext()); 2739 CCInfo.AnalyzeCallResult(Ins, RetCC); 2740 2741 // Copy all of the result registers out of their specified physreg. 2742 for (unsigned i = 0; i != RVLocs.size(); ++i) { 2743 CCValAssign VA = RVLocs[i]; 2744 2745 // Pass 'this' value directly from the argument to return value, to avoid 2746 // reg unit interference 2747 if (i == 0 && isThisReturn) { 2748 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 && 2749 "unexpected return calling convention register assignment"); 2750 InVals.push_back(ThisVal); 2751 continue; 2752 } 2753 2754 SDValue Val = 2755 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 2756 Chain = Val.getValue(1); 2757 InFlag = Val.getValue(2); 2758 2759 switch (VA.getLocInfo()) { 2760 default: 2761 llvm_unreachable("Unknown loc info!"); 2762 case CCValAssign::Full: 2763 break; 2764 case CCValAssign::BCvt: 2765 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 2766 break; 2767 } 2768 2769 InVals.push_back(Val); 2770 } 2771 2772 return Chain; 2773 } 2774 2775 /// Return true if the calling convention is one that we can guarantee TCO for. 2776 static bool canGuaranteeTCO(CallingConv::ID CC) { 2777 return CC == CallingConv::Fast; 2778 } 2779 2780 /// Return true if we might ever do TCO for calls with this calling convention. 2781 static bool mayTailCallThisCC(CallingConv::ID CC) { 2782 switch (CC) { 2783 case CallingConv::C: 2784 case CallingConv::PreserveMost: 2785 case CallingConv::Swift: 2786 return true; 2787 default: 2788 return canGuaranteeTCO(CC); 2789 } 2790 } 2791 2792 bool AArch64TargetLowering::isEligibleForTailCallOptimization( 2793 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 2794 const SmallVectorImpl<ISD::OutputArg> &Outs, 2795 const SmallVectorImpl<SDValue> &OutVals, 2796 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 2797 if (!mayTailCallThisCC(CalleeCC)) 2798 return false; 2799 2800 MachineFunction &MF = DAG.getMachineFunction(); 2801 const Function *CallerF = MF.getFunction(); 2802 CallingConv::ID CallerCC = CallerF->getCallingConv(); 2803 bool CCMatch = CallerCC == CalleeCC; 2804 2805 // Byval parameters hand the function a pointer directly into the stack area 2806 // we want to reuse during a tail call. Working around this *is* possible (see 2807 // X86) but less efficient and uglier in LowerCall. 2808 for (Function::const_arg_iterator i = CallerF->arg_begin(), 2809 e = CallerF->arg_end(); 2810 i != e; ++i) 2811 if (i->hasByValAttr()) 2812 return false; 2813 2814 if (getTargetMachine().Options.GuaranteedTailCallOpt) 2815 return canGuaranteeTCO(CalleeCC) && CCMatch; 2816 2817 // Externally-defined functions with weak linkage should not be 2818 // tail-called on AArch64 when the OS does not support dynamic 2819 // pre-emption of symbols, as the AAELF spec requires normal calls 2820 // to undefined weak functions to be replaced with a NOP or jump to the 2821 // next instruction. The behaviour of branch instructions in this 2822 // situation (as used for tail calls) is implementation-defined, so we 2823 // cannot rely on the linker replacing the tail call with a return. 2824 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 2825 const GlobalValue *GV = G->getGlobal(); 2826 const Triple &TT = getTargetMachine().getTargetTriple(); 2827 if (GV->hasExternalWeakLinkage() && 2828 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 2829 return false; 2830 } 2831 2832 // Now we search for cases where we can use a tail call without changing the 2833 // ABI. Sibcall is used in some places (particularly gcc) to refer to this 2834 // concept. 2835 2836 // I want anyone implementing a new calling convention to think long and hard 2837 // about this assert. 2838 assert((!isVarArg || CalleeCC == CallingConv::C) && 2839 "Unexpected variadic calling convention"); 2840 2841 LLVMContext &C = *DAG.getContext(); 2842 if (isVarArg && !Outs.empty()) { 2843 // At least two cases here: if caller is fastcc then we can't have any 2844 // memory arguments (we'd be expected to clean up the stack afterwards). If 2845 // caller is C then we could potentially use its argument area. 2846 2847 // FIXME: for now we take the most conservative of these in both cases: 2848 // disallow all variadic memory operands. 2849 SmallVector<CCValAssign, 16> ArgLocs; 2850 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2851 2852 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true)); 2853 for (const CCValAssign &ArgLoc : ArgLocs) 2854 if (!ArgLoc.isRegLoc()) 2855 return false; 2856 } 2857 2858 // Check that the call results are passed in the same way. 2859 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 2860 CCAssignFnForCall(CalleeCC, isVarArg), 2861 CCAssignFnForCall(CallerCC, isVarArg))) 2862 return false; 2863 // The callee has to preserve all registers the caller needs to preserve. 2864 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 2865 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 2866 if (!CCMatch) { 2867 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 2868 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 2869 return false; 2870 } 2871 2872 // Nothing more to check if the callee is taking no arguments 2873 if (Outs.empty()) 2874 return true; 2875 2876 SmallVector<CCValAssign, 16> ArgLocs; 2877 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 2878 2879 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 2880 2881 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 2882 2883 // If the stack arguments for this call do not fit into our own save area then 2884 // the call cannot be made tail. 2885 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 2886 return false; 2887 2888 const MachineRegisterInfo &MRI = MF.getRegInfo(); 2889 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 2890 return false; 2891 2892 return true; 2893 } 2894 2895 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain, 2896 SelectionDAG &DAG, 2897 MachineFrameInfo &MFI, 2898 int ClobberedFI) const { 2899 SmallVector<SDValue, 8> ArgChains; 2900 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI); 2901 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1; 2902 2903 // Include the original chain at the beginning of the list. When this is 2904 // used by target LowerCall hooks, this helps legalize find the 2905 // CALLSEQ_BEGIN node. 2906 ArgChains.push_back(Chain); 2907 2908 // Add a chain value for each stack argument corresponding 2909 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(), 2910 UE = DAG.getEntryNode().getNode()->use_end(); 2911 U != UE; ++U) 2912 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 2913 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 2914 if (FI->getIndex() < 0) { 2915 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex()); 2916 int64_t InLastByte = InFirstByte; 2917 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1; 2918 2919 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) || 2920 (FirstByte <= InFirstByte && InFirstByte <= LastByte)) 2921 ArgChains.push_back(SDValue(L, 1)); 2922 } 2923 2924 // Build a tokenfactor for all the chains. 2925 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 2926 } 2927 2928 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC, 2929 bool TailCallOpt) const { 2930 return CallCC == CallingConv::Fast && TailCallOpt; 2931 } 2932 2933 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain, 2934 /// and add input and output parameter nodes. 2935 SDValue 2936 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI, 2937 SmallVectorImpl<SDValue> &InVals) const { 2938 SelectionDAG &DAG = CLI.DAG; 2939 SDLoc &DL = CLI.DL; 2940 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 2941 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 2942 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 2943 SDValue Chain = CLI.Chain; 2944 SDValue Callee = CLI.Callee; 2945 bool &IsTailCall = CLI.IsTailCall; 2946 CallingConv::ID CallConv = CLI.CallConv; 2947 bool IsVarArg = CLI.IsVarArg; 2948 2949 MachineFunction &MF = DAG.getMachineFunction(); 2950 bool IsThisReturn = false; 2951 2952 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 2953 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 2954 bool IsSibCall = false; 2955 2956 if (IsTailCall) { 2957 // Check if it's really possible to do a tail call. 2958 IsTailCall = isEligibleForTailCallOptimization( 2959 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 2960 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall()) 2961 report_fatal_error("failed to perform tail call elimination on a call " 2962 "site marked musttail"); 2963 2964 // A sibling call is one where we're under the usual C ABI and not planning 2965 // to change that but can still do a tail call: 2966 if (!TailCallOpt && IsTailCall) 2967 IsSibCall = true; 2968 2969 if (IsTailCall) 2970 ++NumTailCalls; 2971 } 2972 2973 // Analyze operands of the call, assigning locations to each operand. 2974 SmallVector<CCValAssign, 16> ArgLocs; 2975 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, 2976 *DAG.getContext()); 2977 2978 if (IsVarArg) { 2979 // Handle fixed and variable vector arguments differently. 2980 // Variable vector arguments always go into memory. 2981 unsigned NumArgs = Outs.size(); 2982 2983 for (unsigned i = 0; i != NumArgs; ++i) { 2984 MVT ArgVT = Outs[i].VT; 2985 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 2986 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, 2987 /*IsVarArg=*/ !Outs[i].IsFixed); 2988 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo); 2989 assert(!Res && "Call operand has unhandled type"); 2990 (void)Res; 2991 } 2992 } else { 2993 // At this point, Outs[].VT may already be promoted to i32. To correctly 2994 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 2995 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 2996 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here 2997 // we use a special version of AnalyzeCallOperands to pass in ValVT and 2998 // LocVT. 2999 unsigned NumArgs = Outs.size(); 3000 for (unsigned i = 0; i != NumArgs; ++i) { 3001 MVT ValVT = Outs[i].VT; 3002 // Get type of the original argument. 3003 EVT ActualVT = getValueType(DAG.getDataLayout(), 3004 CLI.getArgs()[Outs[i].OrigArgIndex].Ty, 3005 /*AllowUnknown*/ true); 3006 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT; 3007 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 3008 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 3009 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 3010 ValVT = MVT::i8; 3011 else if (ActualMVT == MVT::i16) 3012 ValVT = MVT::i16; 3013 3014 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 3015 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo); 3016 assert(!Res && "Call operand has unhandled type"); 3017 (void)Res; 3018 } 3019 } 3020 3021 // Get a count of how many bytes are to be pushed on the stack. 3022 unsigned NumBytes = CCInfo.getNextStackOffset(); 3023 3024 if (IsSibCall) { 3025 // Since we're not changing the ABI to make this a tail call, the memory 3026 // operands are already available in the caller's incoming argument space. 3027 NumBytes = 0; 3028 } 3029 3030 // FPDiff is the byte offset of the call's argument area from the callee's. 3031 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3032 // by this amount for a tail call. In a sibling call it must be 0 because the 3033 // caller will deallocate the entire stack and the callee still expects its 3034 // arguments to begin at SP+0. Completely unused for non-tail calls. 3035 int FPDiff = 0; 3036 3037 if (IsTailCall && !IsSibCall) { 3038 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea(); 3039 3040 // Since callee will pop argument stack as a tail call, we must keep the 3041 // popped size 16-byte aligned. 3042 NumBytes = alignTo(NumBytes, 16); 3043 3044 // FPDiff will be negative if this tail call requires more space than we 3045 // would automatically have in our incoming argument space. Positive if we 3046 // can actually shrink the stack. 3047 FPDiff = NumReusableBytes - NumBytes; 3048 3049 // The stack pointer must be 16-byte aligned at all times it's used for a 3050 // memory operation, which in practice means at *all* times and in 3051 // particular across call boundaries. Therefore our own arguments started at 3052 // a 16-byte aligned SP and the delta applied for the tail call should 3053 // satisfy the same constraint. 3054 assert(FPDiff % 16 == 0 && "unaligned stack on tail call"); 3055 } 3056 3057 // Adjust the stack pointer for the new arguments... 3058 // These operations are automatically eliminated by the prolog/epilog pass 3059 if (!IsSibCall) 3060 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL, 3061 true), 3062 DL); 3063 3064 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP, 3065 getPointerTy(DAG.getDataLayout())); 3066 3067 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3068 SmallVector<SDValue, 8> MemOpChains; 3069 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3070 3071 // Walk the register/memloc assignments, inserting copies/loads. 3072 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e; 3073 ++i, ++realArgIdx) { 3074 CCValAssign &VA = ArgLocs[i]; 3075 SDValue Arg = OutVals[realArgIdx]; 3076 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 3077 3078 // Promote the value if needed. 3079 switch (VA.getLocInfo()) { 3080 default: 3081 llvm_unreachable("Unknown loc info!"); 3082 case CCValAssign::Full: 3083 break; 3084 case CCValAssign::SExt: 3085 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3086 break; 3087 case CCValAssign::ZExt: 3088 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3089 break; 3090 case CCValAssign::AExt: 3091 if (Outs[realArgIdx].ArgVT == MVT::i1) { 3092 // AAPCS requires i1 to be zero-extended to 8-bits by the caller. 3093 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 3094 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg); 3095 } 3096 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3097 break; 3098 case CCValAssign::BCvt: 3099 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3100 break; 3101 case CCValAssign::FPExt: 3102 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3103 break; 3104 } 3105 3106 if (VA.isRegLoc()) { 3107 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) { 3108 assert(VA.getLocVT() == MVT::i64 && 3109 "unexpected calling convention register assignment"); 3110 assert(!Ins.empty() && Ins[0].VT == MVT::i64 && 3111 "unexpected use of 'returned'"); 3112 IsThisReturn = true; 3113 } 3114 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3115 } else { 3116 assert(VA.isMemLoc()); 3117 3118 SDValue DstAddr; 3119 MachinePointerInfo DstInfo; 3120 3121 // FIXME: This works on big-endian for composite byvals, which are the 3122 // common case. It should also work for fundamental types too. 3123 uint32_t BEAlign = 0; 3124 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8 3125 : VA.getValVT().getSizeInBits(); 3126 OpSize = (OpSize + 7) / 8; 3127 if (!Subtarget->isLittleEndian() && !Flags.isByVal() && 3128 !Flags.isInConsecutiveRegs()) { 3129 if (OpSize < 8) 3130 BEAlign = 8 - OpSize; 3131 } 3132 unsigned LocMemOffset = VA.getLocMemOffset(); 3133 int32_t Offset = LocMemOffset + BEAlign; 3134 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 3135 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 3136 3137 if (IsTailCall) { 3138 Offset = Offset + FPDiff; 3139 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 3140 3141 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3142 DstInfo = 3143 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 3144 3145 // Make sure any stack arguments overlapping with where we're storing 3146 // are loaded before this eventual operation. Otherwise they'll be 3147 // clobbered. 3148 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI); 3149 } else { 3150 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 3151 3152 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 3153 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(), 3154 LocMemOffset); 3155 } 3156 3157 if (Outs[i].Flags.isByVal()) { 3158 SDValue SizeNode = 3159 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64); 3160 SDValue Cpy = DAG.getMemcpy( 3161 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(), 3162 /*isVol = */ false, /*AlwaysInline = */ false, 3163 /*isTailCall = */ false, 3164 DstInfo, MachinePointerInfo()); 3165 3166 MemOpChains.push_back(Cpy); 3167 } else { 3168 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already 3169 // promoted to a legal register type i32, we should truncate Arg back to 3170 // i1/i8/i16. 3171 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 || 3172 VA.getValVT() == MVT::i16) 3173 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg); 3174 3175 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo); 3176 MemOpChains.push_back(Store); 3177 } 3178 } 3179 } 3180 3181 if (!MemOpChains.empty()) 3182 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3183 3184 // Build a sequence of copy-to-reg nodes chained together with token chain 3185 // and flag operands which copy the outgoing args into the appropriate regs. 3186 SDValue InFlag; 3187 for (auto &RegToPass : RegsToPass) { 3188 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3189 RegToPass.second, InFlag); 3190 InFlag = Chain.getValue(1); 3191 } 3192 3193 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 3194 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 3195 // node so that legalize doesn't hack it. 3196 if (getTargetMachine().getCodeModel() == CodeModel::Large && 3197 Subtarget->isTargetMachO()) { 3198 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3199 const GlobalValue *GV = G->getGlobal(); 3200 bool InternalLinkage = GV->hasInternalLinkage(); 3201 if (InternalLinkage) 3202 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0); 3203 else { 3204 Callee = 3205 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT); 3206 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 3207 } 3208 } else if (ExternalSymbolSDNode *S = 3209 dyn_cast<ExternalSymbolSDNode>(Callee)) { 3210 const char *Sym = S->getSymbol(); 3211 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT); 3212 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 3213 } 3214 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3215 const GlobalValue *GV = G->getGlobal(); 3216 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0); 3217 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 3218 const char *Sym = S->getSymbol(); 3219 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0); 3220 } 3221 3222 // We don't usually want to end the call-sequence here because we would tidy 3223 // the frame up *after* the call, however in the ABI-changing tail-call case 3224 // we've carefully laid out the parameters so that when sp is reset they'll be 3225 // in the correct location. 3226 if (IsTailCall && !IsSibCall) { 3227 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 3228 DAG.getIntPtrConstant(0, DL, true), InFlag, DL); 3229 InFlag = Chain.getValue(1); 3230 } 3231 3232 std::vector<SDValue> Ops; 3233 Ops.push_back(Chain); 3234 Ops.push_back(Callee); 3235 3236 if (IsTailCall) { 3237 // Each tail call may have to adjust the stack by a different amount, so 3238 // this information must travel along with the operation for eventual 3239 // consumption by emitEpilogue. 3240 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3241 } 3242 3243 // Add argument registers to the end of the list so that they are known live 3244 // into the call. 3245 for (auto &RegToPass : RegsToPass) 3246 Ops.push_back(DAG.getRegister(RegToPass.first, 3247 RegToPass.second.getValueType())); 3248 3249 // Add a register mask operand representing the call-preserved registers. 3250 const uint32_t *Mask; 3251 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 3252 if (IsThisReturn) { 3253 // For 'this' returns, use the X0-preserving mask if applicable 3254 Mask = TRI->getThisReturnPreservedMask(MF, CallConv); 3255 if (!Mask) { 3256 IsThisReturn = false; 3257 Mask = TRI->getCallPreservedMask(MF, CallConv); 3258 } 3259 } else 3260 Mask = TRI->getCallPreservedMask(MF, CallConv); 3261 3262 assert(Mask && "Missing call preserved mask for calling convention"); 3263 Ops.push_back(DAG.getRegisterMask(Mask)); 3264 3265 if (InFlag.getNode()) 3266 Ops.push_back(InFlag); 3267 3268 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3269 3270 // If we're doing a tall call, use a TC_RETURN here rather than an 3271 // actual call instruction. 3272 if (IsTailCall) { 3273 MF.getFrameInfo().setHasTailCall(); 3274 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops); 3275 } 3276 3277 // Returns a chain and a flag for retval copy to use. 3278 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops); 3279 InFlag = Chain.getValue(1); 3280 3281 uint64_t CalleePopBytes = 3282 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0; 3283 3284 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 3285 DAG.getIntPtrConstant(CalleePopBytes, DL, true), 3286 InFlag, DL); 3287 if (!Ins.empty()) 3288 InFlag = Chain.getValue(1); 3289 3290 // Handle result values, copying them out of physregs into vregs that we 3291 // return. 3292 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3293 InVals, IsThisReturn, 3294 IsThisReturn ? OutVals[0] : SDValue()); 3295 } 3296 3297 bool AArch64TargetLowering::CanLowerReturn( 3298 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, 3299 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 3300 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 3301 ? RetCC_AArch64_WebKit_JS 3302 : RetCC_AArch64_AAPCS; 3303 SmallVector<CCValAssign, 16> RVLocs; 3304 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 3305 return CCInfo.CheckReturn(Outs, RetCC); 3306 } 3307 3308 SDValue 3309 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 3310 bool isVarArg, 3311 const SmallVectorImpl<ISD::OutputArg> &Outs, 3312 const SmallVectorImpl<SDValue> &OutVals, 3313 const SDLoc &DL, SelectionDAG &DAG) const { 3314 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 3315 ? RetCC_AArch64_WebKit_JS 3316 : RetCC_AArch64_AAPCS; 3317 SmallVector<CCValAssign, 16> RVLocs; 3318 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 3319 *DAG.getContext()); 3320 CCInfo.AnalyzeReturn(Outs, RetCC); 3321 3322 // Copy the result values into the output registers. 3323 SDValue Flag; 3324 SmallVector<SDValue, 4> RetOps(1, Chain); 3325 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size(); 3326 ++i, ++realRVLocIdx) { 3327 CCValAssign &VA = RVLocs[i]; 3328 assert(VA.isRegLoc() && "Can only return in registers!"); 3329 SDValue Arg = OutVals[realRVLocIdx]; 3330 3331 switch (VA.getLocInfo()) { 3332 default: 3333 llvm_unreachable("Unknown loc info!"); 3334 case CCValAssign::Full: 3335 if (Outs[i].ArgVT == MVT::i1) { 3336 // AAPCS requires i1 to be zero-extended to i8 by the producer of the 3337 // value. This is strictly redundant on Darwin (which uses "zeroext 3338 // i1"), but will be optimised out before ISel. 3339 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 3340 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3341 } 3342 break; 3343 case CCValAssign::BCvt: 3344 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3345 break; 3346 } 3347 3348 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 3349 Flag = Chain.getValue(1); 3350 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 3351 } 3352 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 3353 const MCPhysReg *I = 3354 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 3355 if (I) { 3356 for (; *I; ++I) { 3357 if (AArch64::GPR64RegClass.contains(*I)) 3358 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 3359 else if (AArch64::FPR64RegClass.contains(*I)) 3360 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 3361 else 3362 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 3363 } 3364 } 3365 3366 RetOps[0] = Chain; // Update chain. 3367 3368 // Add the flag if we have it. 3369 if (Flag.getNode()) 3370 RetOps.push_back(Flag); 3371 3372 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps); 3373 } 3374 3375 //===----------------------------------------------------------------------===// 3376 // Other Lowering Code 3377 //===----------------------------------------------------------------------===// 3378 3379 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op, 3380 SelectionDAG &DAG) const { 3381 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3382 SDLoc DL(Op); 3383 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op); 3384 const GlobalValue *GV = GN->getGlobal(); 3385 unsigned char OpFlags = 3386 Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); 3387 3388 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 && 3389 "unexpected offset in global node"); 3390 3391 // This also catched the large code model case for Darwin. 3392 if ((OpFlags & AArch64II::MO_GOT) != 0) { 3393 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 3394 // FIXME: Once remat is capable of dealing with instructions with register 3395 // operands, expand this into two nodes instead of using a wrapper node. 3396 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr); 3397 } 3398 3399 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 3400 const unsigned char MO_NC = AArch64II::MO_NC; 3401 return DAG.getNode( 3402 AArch64ISD::WrapperLarge, DL, PtrVT, 3403 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3), 3404 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC), 3405 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC), 3406 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC)); 3407 } else { 3408 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and 3409 // the only correct model on Darwin. 3410 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 3411 OpFlags | AArch64II::MO_PAGE); 3412 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC; 3413 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags); 3414 3415 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi); 3416 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo); 3417 } 3418 } 3419 3420 /// \brief Convert a TLS address reference into the correct sequence of loads 3421 /// and calls to compute the variable's address (for Darwin, currently) and 3422 /// return an SDValue containing the final node. 3423 3424 /// Darwin only has one TLS scheme which must be capable of dealing with the 3425 /// fully general situation, in the worst case. This means: 3426 /// + "extern __thread" declaration. 3427 /// + Defined in a possibly unknown dynamic library. 3428 /// 3429 /// The general system is that each __thread variable has a [3 x i64] descriptor 3430 /// which contains information used by the runtime to calculate the address. The 3431 /// only part of this the compiler needs to know about is the first xword, which 3432 /// contains a function pointer that must be called with the address of the 3433 /// entire descriptor in "x0". 3434 /// 3435 /// Since this descriptor may be in a different unit, in general even the 3436 /// descriptor must be accessed via an indirect load. The "ideal" code sequence 3437 /// is: 3438 /// adrp x0, _var@TLVPPAGE 3439 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor 3440 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor, 3441 /// ; the function pointer 3442 /// blr x1 ; Uses descriptor address in x0 3443 /// ; Address of _var is now in x0. 3444 /// 3445 /// If the address of _var's descriptor *is* known to the linker, then it can 3446 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for 3447 /// a slight efficiency gain. 3448 SDValue 3449 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op, 3450 SelectionDAG &DAG) const { 3451 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin"); 3452 3453 SDLoc DL(Op); 3454 MVT PtrVT = getPointerTy(DAG.getDataLayout()); 3455 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 3456 3457 SDValue TLVPAddr = 3458 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 3459 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr); 3460 3461 // The first entry in the descriptor is a function pointer that we must call 3462 // to obtain the address of the variable. 3463 SDValue Chain = DAG.getEntryNode(); 3464 SDValue FuncTLVGet = DAG.getLoad( 3465 MVT::i64, DL, Chain, DescAddr, 3466 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 3467 /* Alignment = */ 8, 3468 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant | 3469 MachineMemOperand::MODereferenceable); 3470 Chain = FuncTLVGet.getValue(1); 3471 3472 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 3473 MFI.setAdjustsStack(true); 3474 3475 // TLS calls preserve all registers except those that absolutely must be 3476 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be 3477 // silly). 3478 const uint32_t *Mask = 3479 Subtarget->getRegisterInfo()->getTLSCallPreservedMask(); 3480 3481 // Finally, we can make the call. This is just a degenerate version of a 3482 // normal AArch64 call node: x0 takes the address of the descriptor, and 3483 // returns the address of the variable in this thread. 3484 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue()); 3485 Chain = 3486 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 3487 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64), 3488 DAG.getRegisterMask(Mask), Chain.getValue(1)); 3489 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1)); 3490 } 3491 3492 /// When accessing thread-local variables under either the general-dynamic or 3493 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will 3494 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry 3495 /// is a function pointer to carry out the resolution. 3496 /// 3497 /// The sequence is: 3498 /// adrp x0, :tlsdesc:var 3499 /// ldr x1, [x0, #:tlsdesc_lo12:var] 3500 /// add x0, x0, #:tlsdesc_lo12:var 3501 /// .tlsdesccall var 3502 /// blr x1 3503 /// (TPIDR_EL0 offset now in x0) 3504 /// 3505 /// The above sequence must be produced unscheduled, to enable the linker to 3506 /// optimize/relax this sequence. 3507 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the 3508 /// above sequence, and expanded really late in the compilation flow, to ensure 3509 /// the sequence is produced as per above. 3510 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, 3511 const SDLoc &DL, 3512 SelectionDAG &DAG) const { 3513 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3514 3515 SDValue Chain = DAG.getEntryNode(); 3516 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3517 3518 Chain = 3519 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr}); 3520 SDValue Glue = Chain.getValue(1); 3521 3522 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue); 3523 } 3524 3525 SDValue 3526 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op, 3527 SelectionDAG &DAG) const { 3528 assert(Subtarget->isTargetELF() && "This function expects an ELF target"); 3529 assert(getTargetMachine().getCodeModel() == CodeModel::Small && 3530 "ELF TLS only supported in small memory model"); 3531 // Different choices can be made for the maximum size of the TLS area for a 3532 // module. For the small address model, the default TLS size is 16MiB and the 3533 // maximum TLS size is 4GiB. 3534 // FIXME: add -mtls-size command line option and make it control the 16MiB 3535 // vs. 4GiB code sequence generation. 3536 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 3537 3538 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal()); 3539 3540 if (DAG.getTarget().Options.EmulatedTLS) 3541 return LowerToTLSEmulatedModel(GA, DAG); 3542 3543 if (!EnableAArch64ELFLocalDynamicTLSGeneration) { 3544 if (Model == TLSModel::LocalDynamic) 3545 Model = TLSModel::GeneralDynamic; 3546 } 3547 3548 SDValue TPOff; 3549 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3550 SDLoc DL(Op); 3551 const GlobalValue *GV = GA->getGlobal(); 3552 3553 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT); 3554 3555 if (Model == TLSModel::LocalExec) { 3556 SDValue HiVar = DAG.getTargetGlobalAddress( 3557 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 3558 SDValue LoVar = DAG.getTargetGlobalAddress( 3559 GV, DL, PtrVT, 0, 3560 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 3561 3562 SDValue TPWithOff_lo = 3563 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase, 3564 HiVar, 3565 DAG.getTargetConstant(0, DL, MVT::i32)), 3566 0); 3567 SDValue TPWithOff = 3568 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo, 3569 LoVar, 3570 DAG.getTargetConstant(0, DL, MVT::i32)), 3571 0); 3572 return TPWithOff; 3573 } else if (Model == TLSModel::InitialExec) { 3574 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 3575 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff); 3576 } else if (Model == TLSModel::LocalDynamic) { 3577 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS 3578 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate 3579 // the beginning of the module's TLS region, followed by a DTPREL offset 3580 // calculation. 3581 3582 // These accesses will need deduplicating if there's more than one. 3583 AArch64FunctionInfo *MFI = 3584 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 3585 MFI->incNumLocalDynamicTLSAccesses(); 3586 3587 // The call needs a relocation too for linker relaxation. It doesn't make 3588 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 3589 // the address. 3590 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT, 3591 AArch64II::MO_TLS); 3592 3593 // Now we can calculate the offset from TPIDR_EL0 to this module's 3594 // thread-local area. 3595 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 3596 3597 // Now use :dtprel_whatever: operations to calculate this variable's offset 3598 // in its thread-storage area. 3599 SDValue HiVar = DAG.getTargetGlobalAddress( 3600 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 3601 SDValue LoVar = DAG.getTargetGlobalAddress( 3602 GV, DL, MVT::i64, 0, 3603 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 3604 3605 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar, 3606 DAG.getTargetConstant(0, DL, MVT::i32)), 3607 0); 3608 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar, 3609 DAG.getTargetConstant(0, DL, MVT::i32)), 3610 0); 3611 } else if (Model == TLSModel::GeneralDynamic) { 3612 // The call needs a relocation too for linker relaxation. It doesn't make 3613 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 3614 // the address. 3615 SDValue SymAddr = 3616 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 3617 3618 // Finally we can make a call to calculate the offset from tpidr_el0. 3619 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 3620 } else 3621 llvm_unreachable("Unsupported ELF TLS access model"); 3622 3623 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 3624 } 3625 3626 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op, 3627 SelectionDAG &DAG) const { 3628 if (Subtarget->isTargetDarwin()) 3629 return LowerDarwinGlobalTLSAddress(Op, DAG); 3630 else if (Subtarget->isTargetELF()) 3631 return LowerELFGlobalTLSAddress(Op, DAG); 3632 3633 llvm_unreachable("Unexpected platform trying to use TLS"); 3634 } 3635 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 3636 SDValue Chain = Op.getOperand(0); 3637 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 3638 SDValue LHS = Op.getOperand(2); 3639 SDValue RHS = Op.getOperand(3); 3640 SDValue Dest = Op.getOperand(4); 3641 SDLoc dl(Op); 3642 3643 // Handle f128 first, since lowering it will result in comparing the return 3644 // value of a libcall against zero, which is just what the rest of LowerBR_CC 3645 // is expecting to deal with. 3646 if (LHS.getValueType() == MVT::f128) { 3647 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); 3648 3649 // If softenSetCCOperands returned a scalar, we need to compare the result 3650 // against zero to select between true and false values. 3651 if (!RHS.getNode()) { 3652 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 3653 CC = ISD::SETNE; 3654 } 3655 } 3656 3657 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 3658 // instruction. 3659 unsigned Opc = LHS.getOpcode(); 3660 if (LHS.getResNo() == 1 && isOneConstant(RHS) && 3661 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 3662 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) { 3663 assert((CC == ISD::SETEQ || CC == ISD::SETNE) && 3664 "Unexpected condition code."); 3665 // Only lower legal XALUO ops. 3666 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 3667 return SDValue(); 3668 3669 // The actual operation with overflow check. 3670 AArch64CC::CondCode OFCC; 3671 SDValue Value, Overflow; 3672 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG); 3673 3674 if (CC == ISD::SETNE) 3675 OFCC = getInvertedCondCode(OFCC); 3676 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32); 3677 3678 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 3679 Overflow); 3680 } 3681 3682 if (LHS.getValueType().isInteger()) { 3683 assert((LHS.getValueType() == RHS.getValueType()) && 3684 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 3685 3686 // If the RHS of the comparison is zero, we can potentially fold this 3687 // to a specialized branch. 3688 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS); 3689 if (RHSC && RHSC->getZExtValue() == 0) { 3690 if (CC == ISD::SETEQ) { 3691 // See if we can use a TBZ to fold in an AND as well. 3692 // TBZ has a smaller branch displacement than CBZ. If the offset is 3693 // out of bounds, a late MI-layer pass rewrites branches. 3694 // 403.gcc is an example that hits this case. 3695 if (LHS.getOpcode() == ISD::AND && 3696 isa<ConstantSDNode>(LHS.getOperand(1)) && 3697 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 3698 SDValue Test = LHS.getOperand(0); 3699 uint64_t Mask = LHS.getConstantOperandVal(1); 3700 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test, 3701 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 3702 Dest); 3703 } 3704 3705 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest); 3706 } else if (CC == ISD::SETNE) { 3707 // See if we can use a TBZ to fold in an AND as well. 3708 // TBZ has a smaller branch displacement than CBZ. If the offset is 3709 // out of bounds, a late MI-layer pass rewrites branches. 3710 // 403.gcc is an example that hits this case. 3711 if (LHS.getOpcode() == ISD::AND && 3712 isa<ConstantSDNode>(LHS.getOperand(1)) && 3713 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 3714 SDValue Test = LHS.getOperand(0); 3715 uint64_t Mask = LHS.getConstantOperandVal(1); 3716 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test, 3717 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 3718 Dest); 3719 } 3720 3721 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest); 3722 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) { 3723 // Don't combine AND since emitComparison converts the AND to an ANDS 3724 // (a.k.a. TST) and the test in the test bit and branch instruction 3725 // becomes redundant. This would also increase register pressure. 3726 uint64_t Mask = LHS.getValueSizeInBits() - 1; 3727 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS, 3728 DAG.getConstant(Mask, dl, MVT::i64), Dest); 3729 } 3730 } 3731 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT && 3732 LHS.getOpcode() != ISD::AND) { 3733 // Don't combine AND since emitComparison converts the AND to an ANDS 3734 // (a.k.a. TST) and the test in the test bit and branch instruction 3735 // becomes redundant. This would also increase register pressure. 3736 uint64_t Mask = LHS.getValueSizeInBits() - 1; 3737 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS, 3738 DAG.getConstant(Mask, dl, MVT::i64), Dest); 3739 } 3740 3741 SDValue CCVal; 3742 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 3743 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 3744 Cmp); 3745 } 3746 3747 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 3748 3749 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 3750 // clean. Some of them require two branches to implement. 3751 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 3752 AArch64CC::CondCode CC1, CC2; 3753 changeFPCCToAArch64CC(CC, CC1, CC2); 3754 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 3755 SDValue BR1 = 3756 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp); 3757 if (CC2 != AArch64CC::AL) { 3758 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 3759 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val, 3760 Cmp); 3761 } 3762 3763 return BR1; 3764 } 3765 3766 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op, 3767 SelectionDAG &DAG) const { 3768 EVT VT = Op.getValueType(); 3769 SDLoc DL(Op); 3770 3771 SDValue In1 = Op.getOperand(0); 3772 SDValue In2 = Op.getOperand(1); 3773 EVT SrcVT = In2.getValueType(); 3774 3775 if (SrcVT.bitsLT(VT)) 3776 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2); 3777 else if (SrcVT.bitsGT(VT)) 3778 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL)); 3779 3780 EVT VecVT; 3781 EVT EltVT; 3782 uint64_t EltMask; 3783 SDValue VecVal1, VecVal2; 3784 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) { 3785 EltVT = MVT::i32; 3786 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32); 3787 EltMask = 0x80000000ULL; 3788 3789 if (!VT.isVector()) { 3790 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT, 3791 DAG.getUNDEF(VecVT), In1); 3792 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT, 3793 DAG.getUNDEF(VecVT), In2); 3794 } else { 3795 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1); 3796 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2); 3797 } 3798 } else if (VT == MVT::f64 || VT == MVT::v2f64) { 3799 EltVT = MVT::i64; 3800 VecVT = MVT::v2i64; 3801 3802 // We want to materialize a mask with the high bit set, but the AdvSIMD 3803 // immediate moves cannot materialize that in a single instruction for 3804 // 64-bit elements. Instead, materialize zero and then negate it. 3805 EltMask = 0; 3806 3807 if (!VT.isVector()) { 3808 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT, 3809 DAG.getUNDEF(VecVT), In1); 3810 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT, 3811 DAG.getUNDEF(VecVT), In2); 3812 } else { 3813 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1); 3814 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2); 3815 } 3816 } else { 3817 llvm_unreachable("Invalid type for copysign!"); 3818 } 3819 3820 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT); 3821 3822 // If we couldn't materialize the mask above, then the mask vector will be 3823 // the zero vector, and we need to negate it here. 3824 if (VT == MVT::f64 || VT == MVT::v2f64) { 3825 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec); 3826 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec); 3827 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec); 3828 } 3829 3830 SDValue Sel = 3831 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec); 3832 3833 if (VT == MVT::f32) 3834 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel); 3835 else if (VT == MVT::f64) 3836 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel); 3837 else 3838 return DAG.getNode(ISD::BITCAST, DL, VT, Sel); 3839 } 3840 3841 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const { 3842 if (DAG.getMachineFunction().getFunction()->hasFnAttribute( 3843 Attribute::NoImplicitFloat)) 3844 return SDValue(); 3845 3846 if (!Subtarget->hasNEON()) 3847 return SDValue(); 3848 3849 // While there is no integer popcount instruction, it can 3850 // be more efficiently lowered to the following sequence that uses 3851 // AdvSIMD registers/instructions as long as the copies to/from 3852 // the AdvSIMD registers are cheap. 3853 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd 3854 // CNT V0.8B, V0.8B // 8xbyte pop-counts 3855 // ADDV B0, V0.8B // sum 8xbyte pop-counts 3856 // UMOV X0, V0.B[0] // copy byte result back to integer reg 3857 SDValue Val = Op.getOperand(0); 3858 SDLoc DL(Op); 3859 EVT VT = Op.getValueType(); 3860 3861 if (VT == MVT::i32) 3862 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val); 3863 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val); 3864 3865 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val); 3866 SDValue UaddLV = DAG.getNode( 3867 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, 3868 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop); 3869 3870 if (VT == MVT::i64) 3871 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV); 3872 return UaddLV; 3873 } 3874 3875 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 3876 3877 if (Op.getValueType().isVector()) 3878 return LowerVSETCC(Op, DAG); 3879 3880 SDValue LHS = Op.getOperand(0); 3881 SDValue RHS = Op.getOperand(1); 3882 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 3883 SDLoc dl(Op); 3884 3885 // We chose ZeroOrOneBooleanContents, so use zero and one. 3886 EVT VT = Op.getValueType(); 3887 SDValue TVal = DAG.getConstant(1, dl, VT); 3888 SDValue FVal = DAG.getConstant(0, dl, VT); 3889 3890 // Handle f128 first, since one possible outcome is a normal integer 3891 // comparison which gets picked up by the next if statement. 3892 if (LHS.getValueType() == MVT::f128) { 3893 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); 3894 3895 // If softenSetCCOperands returned a scalar, use it. 3896 if (!RHS.getNode()) { 3897 assert(LHS.getValueType() == Op.getValueType() && 3898 "Unexpected setcc expansion!"); 3899 return LHS; 3900 } 3901 } 3902 3903 if (LHS.getValueType().isInteger()) { 3904 SDValue CCVal; 3905 SDValue Cmp = 3906 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl); 3907 3908 // Note that we inverted the condition above, so we reverse the order of 3909 // the true and false operands here. This will allow the setcc to be 3910 // matched to a single CSINC instruction. 3911 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp); 3912 } 3913 3914 // Now we know we're dealing with FP values. 3915 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 3916 3917 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead 3918 // and do the comparison. 3919 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 3920 3921 AArch64CC::CondCode CC1, CC2; 3922 changeFPCCToAArch64CC(CC, CC1, CC2); 3923 if (CC2 == AArch64CC::AL) { 3924 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2); 3925 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 3926 3927 // Note that we inverted the condition above, so we reverse the order of 3928 // the true and false operands here. This will allow the setcc to be 3929 // matched to a single CSINC instruction. 3930 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp); 3931 } else { 3932 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't 3933 // totally clean. Some of them require two CSELs to implement. As is in 3934 // this case, we emit the first CSEL and then emit a second using the output 3935 // of the first as the RHS. We're effectively OR'ing the two CC's together. 3936 3937 // FIXME: It would be nice if we could match the two CSELs to two CSINCs. 3938 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 3939 SDValue CS1 = 3940 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 3941 3942 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 3943 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 3944 } 3945 } 3946 3947 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS, 3948 SDValue RHS, SDValue TVal, 3949 SDValue FVal, const SDLoc &dl, 3950 SelectionDAG &DAG) const { 3951 // Handle f128 first, because it will result in a comparison of some RTLIB 3952 // call result against zero. 3953 if (LHS.getValueType() == MVT::f128) { 3954 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); 3955 3956 // If softenSetCCOperands returned a scalar, we need to compare the result 3957 // against zero to select between true and false values. 3958 if (!RHS.getNode()) { 3959 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 3960 CC = ISD::SETNE; 3961 } 3962 } 3963 3964 // Also handle f16, for which we need to do a f32 comparison. 3965 if (LHS.getValueType() == MVT::f16) { 3966 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 3967 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 3968 } 3969 3970 // Next, handle integers. 3971 if (LHS.getValueType().isInteger()) { 3972 assert((LHS.getValueType() == RHS.getValueType()) && 3973 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 3974 3975 unsigned Opcode = AArch64ISD::CSEL; 3976 3977 // If both the TVal and the FVal are constants, see if we can swap them in 3978 // order to for a CSINV or CSINC out of them. 3979 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 3980 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 3981 3982 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) { 3983 std::swap(TVal, FVal); 3984 std::swap(CTVal, CFVal); 3985 CC = ISD::getSetCCInverse(CC, true); 3986 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) { 3987 std::swap(TVal, FVal); 3988 std::swap(CTVal, CFVal); 3989 CC = ISD::getSetCCInverse(CC, true); 3990 } else if (TVal.getOpcode() == ISD::XOR) { 3991 // If TVal is a NOT we want to swap TVal and FVal so that we can match 3992 // with a CSINV rather than a CSEL. 3993 if (isAllOnesConstant(TVal.getOperand(1))) { 3994 std::swap(TVal, FVal); 3995 std::swap(CTVal, CFVal); 3996 CC = ISD::getSetCCInverse(CC, true); 3997 } 3998 } else if (TVal.getOpcode() == ISD::SUB) { 3999 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so 4000 // that we can match with a CSNEG rather than a CSEL. 4001 if (isNullConstant(TVal.getOperand(0))) { 4002 std::swap(TVal, FVal); 4003 std::swap(CTVal, CFVal); 4004 CC = ISD::getSetCCInverse(CC, true); 4005 } 4006 } else if (CTVal && CFVal) { 4007 const int64_t TrueVal = CTVal->getSExtValue(); 4008 const int64_t FalseVal = CFVal->getSExtValue(); 4009 bool Swap = false; 4010 4011 // If both TVal and FVal are constants, see if FVal is the 4012 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC 4013 // instead of a CSEL in that case. 4014 if (TrueVal == ~FalseVal) { 4015 Opcode = AArch64ISD::CSINV; 4016 } else if (TrueVal == -FalseVal) { 4017 Opcode = AArch64ISD::CSNEG; 4018 } else if (TVal.getValueType() == MVT::i32) { 4019 // If our operands are only 32-bit wide, make sure we use 32-bit 4020 // arithmetic for the check whether we can use CSINC. This ensures that 4021 // the addition in the check will wrap around properly in case there is 4022 // an overflow (which would not be the case if we do the check with 4023 // 64-bit arithmetic). 4024 const uint32_t TrueVal32 = CTVal->getZExtValue(); 4025 const uint32_t FalseVal32 = CFVal->getZExtValue(); 4026 4027 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) { 4028 Opcode = AArch64ISD::CSINC; 4029 4030 if (TrueVal32 > FalseVal32) { 4031 Swap = true; 4032 } 4033 } 4034 // 64-bit check whether we can use CSINC. 4035 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) { 4036 Opcode = AArch64ISD::CSINC; 4037 4038 if (TrueVal > FalseVal) { 4039 Swap = true; 4040 } 4041 } 4042 4043 // Swap TVal and FVal if necessary. 4044 if (Swap) { 4045 std::swap(TVal, FVal); 4046 std::swap(CTVal, CFVal); 4047 CC = ISD::getSetCCInverse(CC, true); 4048 } 4049 4050 if (Opcode != AArch64ISD::CSEL) { 4051 // Drop FVal since we can get its value by simply inverting/negating 4052 // TVal. 4053 FVal = TVal; 4054 } 4055 } 4056 4057 // Avoid materializing a constant when possible by reusing a known value in 4058 // a register. However, don't perform this optimization if the known value 4059 // is one, zero or negative one in the case of a CSEL. We can always 4060 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the 4061 // FVal, respectively. 4062 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS); 4063 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() && 4064 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) { 4065 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 4066 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to 4067 // "a != C ? x : a" to avoid materializing C. 4068 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ) 4069 TVal = LHS; 4070 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE) 4071 FVal = LHS; 4072 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) { 4073 assert (CTVal && CFVal && "Expected constant operands for CSNEG."); 4074 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to 4075 // avoid materializing C. 4076 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 4077 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) { 4078 Opcode = AArch64ISD::CSINV; 4079 TVal = LHS; 4080 FVal = DAG.getConstant(0, dl, FVal.getValueType()); 4081 } 4082 } 4083 4084 SDValue CCVal; 4085 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 4086 4087 EVT VT = TVal.getValueType(); 4088 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp); 4089 } 4090 4091 // Now we know we're dealing with FP values. 4092 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64); 4093 assert(LHS.getValueType() == RHS.getValueType()); 4094 EVT VT = TVal.getValueType(); 4095 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 4096 4097 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 4098 // clean. Some of them require two CSELs to implement. 4099 AArch64CC::CondCode CC1, CC2; 4100 changeFPCCToAArch64CC(CC, CC1, CC2); 4101 4102 if (DAG.getTarget().Options.UnsafeFPMath) { 4103 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and 4104 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0. 4105 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS); 4106 if (RHSVal && RHSVal->isZero()) { 4107 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal); 4108 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal); 4109 4110 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) && 4111 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType()) 4112 TVal = LHS; 4113 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) && 4114 CFVal && CFVal->isZero() && 4115 FVal.getValueType() == LHS.getValueType()) 4116 FVal = LHS; 4117 } 4118 } 4119 4120 // Emit first, and possibly only, CSEL. 4121 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 4122 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 4123 4124 // If we need a second CSEL, emit it, using the output of the first as the 4125 // RHS. We're effectively OR'ing the two CC's together. 4126 if (CC2 != AArch64CC::AL) { 4127 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 4128 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 4129 } 4130 4131 // Otherwise, return the output of the first CSEL. 4132 return CS1; 4133 } 4134 4135 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op, 4136 SelectionDAG &DAG) const { 4137 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4138 SDValue LHS = Op.getOperand(0); 4139 SDValue RHS = Op.getOperand(1); 4140 SDValue TVal = Op.getOperand(2); 4141 SDValue FVal = Op.getOperand(3); 4142 SDLoc DL(Op); 4143 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 4144 } 4145 4146 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op, 4147 SelectionDAG &DAG) const { 4148 SDValue CCVal = Op->getOperand(0); 4149 SDValue TVal = Op->getOperand(1); 4150 SDValue FVal = Op->getOperand(2); 4151 SDLoc DL(Op); 4152 4153 unsigned Opc = CCVal.getOpcode(); 4154 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select 4155 // instruction. 4156 if (CCVal.getResNo() == 1 && 4157 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 4158 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) { 4159 // Only lower legal XALUO ops. 4160 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0))) 4161 return SDValue(); 4162 4163 AArch64CC::CondCode OFCC; 4164 SDValue Value, Overflow; 4165 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG); 4166 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32); 4167 4168 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, 4169 CCVal, Overflow); 4170 } 4171 4172 // Lower it the same way as we would lower a SELECT_CC node. 4173 ISD::CondCode CC; 4174 SDValue LHS, RHS; 4175 if (CCVal.getOpcode() == ISD::SETCC) { 4176 LHS = CCVal.getOperand(0); 4177 RHS = CCVal.getOperand(1); 4178 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get(); 4179 } else { 4180 LHS = CCVal; 4181 RHS = DAG.getConstant(0, DL, CCVal.getValueType()); 4182 CC = ISD::SETNE; 4183 } 4184 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 4185 } 4186 4187 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op, 4188 SelectionDAG &DAG) const { 4189 // Jump table entries as PC relative offsets. No additional tweaking 4190 // is necessary here. Just get the address of the jump table. 4191 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 4192 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4193 SDLoc DL(Op); 4194 4195 if (getTargetMachine().getCodeModel() == CodeModel::Large && 4196 !Subtarget->isTargetMachO()) { 4197 const unsigned char MO_NC = AArch64II::MO_NC; 4198 return DAG.getNode( 4199 AArch64ISD::WrapperLarge, DL, PtrVT, 4200 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3), 4201 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC), 4202 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC), 4203 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 4204 AArch64II::MO_G0 | MO_NC)); 4205 } 4206 4207 SDValue Hi = 4208 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE); 4209 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, 4210 AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 4211 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi); 4212 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo); 4213 } 4214 4215 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op, 4216 SelectionDAG &DAG) const { 4217 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 4218 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4219 SDLoc DL(Op); 4220 4221 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 4222 // Use the GOT for the large code model on iOS. 4223 if (Subtarget->isTargetMachO()) { 4224 SDValue GotAddr = DAG.getTargetConstantPool( 4225 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), 4226 AArch64II::MO_GOT); 4227 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr); 4228 } 4229 4230 const unsigned char MO_NC = AArch64II::MO_NC; 4231 return DAG.getNode( 4232 AArch64ISD::WrapperLarge, DL, PtrVT, 4233 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(), 4234 CP->getOffset(), AArch64II::MO_G3), 4235 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(), 4236 CP->getOffset(), AArch64II::MO_G2 | MO_NC), 4237 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(), 4238 CP->getOffset(), AArch64II::MO_G1 | MO_NC), 4239 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(), 4240 CP->getOffset(), AArch64II::MO_G0 | MO_NC)); 4241 } else { 4242 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on 4243 // ELF, the only valid one on Darwin. 4244 SDValue Hi = 4245 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(), 4246 CP->getOffset(), AArch64II::MO_PAGE); 4247 SDValue Lo = DAG.getTargetConstantPool( 4248 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), 4249 AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 4250 4251 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi); 4252 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo); 4253 } 4254 } 4255 4256 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op, 4257 SelectionDAG &DAG) const { 4258 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress(); 4259 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4260 SDLoc DL(Op); 4261 if (getTargetMachine().getCodeModel() == CodeModel::Large && 4262 !Subtarget->isTargetMachO()) { 4263 const unsigned char MO_NC = AArch64II::MO_NC; 4264 return DAG.getNode( 4265 AArch64ISD::WrapperLarge, DL, PtrVT, 4266 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3), 4267 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC), 4268 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC), 4269 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC)); 4270 } else { 4271 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE); 4272 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF | 4273 AArch64II::MO_NC); 4274 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi); 4275 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo); 4276 } 4277 } 4278 4279 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op, 4280 SelectionDAG &DAG) const { 4281 AArch64FunctionInfo *FuncInfo = 4282 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 4283 4284 SDLoc DL(Op); 4285 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), 4286 getPointerTy(DAG.getDataLayout())); 4287 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4288 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 4289 MachinePointerInfo(SV)); 4290 } 4291 4292 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op, 4293 SelectionDAG &DAG) const { 4294 // The layout of the va_list struct is specified in the AArch64 Procedure Call 4295 // Standard, section B.3. 4296 MachineFunction &MF = DAG.getMachineFunction(); 4297 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 4298 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4299 SDLoc DL(Op); 4300 4301 SDValue Chain = Op.getOperand(0); 4302 SDValue VAList = Op.getOperand(1); 4303 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4304 SmallVector<SDValue, 4> MemOps; 4305 4306 // void *__stack at offset 0 4307 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT); 4308 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList, 4309 MachinePointerInfo(SV), /* Alignment = */ 8)); 4310 4311 // void *__gr_top at offset 8 4312 int GPRSize = FuncInfo->getVarArgsGPRSize(); 4313 if (GPRSize > 0) { 4314 SDValue GRTop, GRTopAddr; 4315 4316 GRTopAddr = 4317 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT)); 4318 4319 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT); 4320 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop, 4321 DAG.getConstant(GPRSize, DL, PtrVT)); 4322 4323 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr, 4324 MachinePointerInfo(SV, 8), 4325 /* Alignment = */ 8)); 4326 } 4327 4328 // void *__vr_top at offset 16 4329 int FPRSize = FuncInfo->getVarArgsFPRSize(); 4330 if (FPRSize > 0) { 4331 SDValue VRTop, VRTopAddr; 4332 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 4333 DAG.getConstant(16, DL, PtrVT)); 4334 4335 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT); 4336 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop, 4337 DAG.getConstant(FPRSize, DL, PtrVT)); 4338 4339 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr, 4340 MachinePointerInfo(SV, 16), 4341 /* Alignment = */ 8)); 4342 } 4343 4344 // int __gr_offs at offset 24 4345 SDValue GROffsAddr = 4346 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT)); 4347 MemOps.push_back(DAG.getStore( 4348 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr, 4349 MachinePointerInfo(SV, 24), /* Alignment = */ 4)); 4350 4351 // int __vr_offs at offset 28 4352 SDValue VROffsAddr = 4353 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT)); 4354 MemOps.push_back(DAG.getStore( 4355 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr, 4356 MachinePointerInfo(SV, 28), /* Alignment = */ 4)); 4357 4358 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 4359 } 4360 4361 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op, 4362 SelectionDAG &DAG) const { 4363 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG) 4364 : LowerAAPCS_VASTART(Op, DAG); 4365 } 4366 4367 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op, 4368 SelectionDAG &DAG) const { 4369 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single 4370 // pointer. 4371 SDLoc DL(Op); 4372 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32; 4373 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 4374 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 4375 4376 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), 4377 Op.getOperand(2), 4378 DAG.getConstant(VaListSize, DL, MVT::i32), 4379 8, false, false, false, MachinePointerInfo(DestSV), 4380 MachinePointerInfo(SrcSV)); 4381 } 4382 4383 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 4384 assert(Subtarget->isTargetDarwin() && 4385 "automatic va_arg instruction only works on Darwin"); 4386 4387 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 4388 EVT VT = Op.getValueType(); 4389 SDLoc DL(Op); 4390 SDValue Chain = Op.getOperand(0); 4391 SDValue Addr = Op.getOperand(1); 4392 unsigned Align = Op.getConstantOperandVal(3); 4393 auto PtrVT = getPointerTy(DAG.getDataLayout()); 4394 4395 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V)); 4396 Chain = VAList.getValue(1); 4397 4398 if (Align > 8) { 4399 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2"); 4400 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 4401 DAG.getConstant(Align - 1, DL, PtrVT)); 4402 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList, 4403 DAG.getConstant(-(int64_t)Align, DL, PtrVT)); 4404 } 4405 4406 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 4407 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy); 4408 4409 // Scalar integer and FP values smaller than 64 bits are implicitly extended 4410 // up to 64 bits. At the very least, we have to increase the striding of the 4411 // vaargs list to match this, and for FP values we need to introduce 4412 // FP_ROUND nodes as well. 4413 if (VT.isInteger() && !VT.isVector()) 4414 ArgSize = 8; 4415 bool NeedFPTrunc = false; 4416 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) { 4417 ArgSize = 8; 4418 NeedFPTrunc = true; 4419 } 4420 4421 // Increment the pointer, VAList, to the next vaarg 4422 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 4423 DAG.getConstant(ArgSize, DL, PtrVT)); 4424 // Store the incremented VAList to the legalized pointer 4425 SDValue APStore = 4426 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V)); 4427 4428 // Load the actual argument out of the pointer VAList 4429 if (NeedFPTrunc) { 4430 // Load the value as an f64. 4431 SDValue WideFP = 4432 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo()); 4433 // Round the value down to an f32. 4434 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0), 4435 DAG.getIntPtrConstant(1, DL)); 4436 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) }; 4437 // Merge the rounded value with the chain output of the load. 4438 return DAG.getMergeValues(Ops, DL); 4439 } 4440 4441 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo()); 4442 } 4443 4444 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op, 4445 SelectionDAG &DAG) const { 4446 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 4447 MFI.setFrameAddressIsTaken(true); 4448 4449 EVT VT = Op.getValueType(); 4450 SDLoc DL(Op); 4451 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4452 SDValue FrameAddr = 4453 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT); 4454 while (Depth--) 4455 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr, 4456 MachinePointerInfo()); 4457 return FrameAddr; 4458 } 4459 4460 // FIXME? Maybe this could be a TableGen attribute on some registers and 4461 // this table could be generated automatically from RegInfo. 4462 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT, 4463 SelectionDAG &DAG) const { 4464 unsigned Reg = StringSwitch<unsigned>(RegName) 4465 .Case("sp", AArch64::SP) 4466 .Default(0); 4467 if (Reg) 4468 return Reg; 4469 report_fatal_error(Twine("Invalid register name \"" 4470 + StringRef(RegName) + "\".")); 4471 } 4472 4473 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op, 4474 SelectionDAG &DAG) const { 4475 MachineFunction &MF = DAG.getMachineFunction(); 4476 MachineFrameInfo &MFI = MF.getFrameInfo(); 4477 MFI.setReturnAddressIsTaken(true); 4478 4479 EVT VT = Op.getValueType(); 4480 SDLoc DL(Op); 4481 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4482 if (Depth) { 4483 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 4484 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout())); 4485 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 4486 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 4487 MachinePointerInfo()); 4488 } 4489 4490 // Return LR, which contains the return address. Mark it an implicit live-in. 4491 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass); 4492 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 4493 } 4494 4495 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 4496 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 4497 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op, 4498 SelectionDAG &DAG) const { 4499 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4500 EVT VT = Op.getValueType(); 4501 unsigned VTBits = VT.getSizeInBits(); 4502 SDLoc dl(Op); 4503 SDValue ShOpLo = Op.getOperand(0); 4504 SDValue ShOpHi = Op.getOperand(1); 4505 SDValue ShAmt = Op.getOperand(2); 4506 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 4507 4508 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 4509 4510 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 4511 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 4512 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 4513 4514 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which 4515 // is "undef". We wanted 0, so CSEL it directly. 4516 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 4517 ISD::SETEQ, dl, DAG); 4518 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 4519 HiBitsForLo = 4520 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 4521 HiBitsForLo, CCVal, Cmp); 4522 4523 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 4524 DAG.getConstant(VTBits, dl, MVT::i64)); 4525 4526 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 4527 SDValue LoForNormalShift = 4528 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo); 4529 4530 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 4531 dl, DAG); 4532 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 4533 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 4534 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 4535 LoForNormalShift, CCVal, Cmp); 4536 4537 // AArch64 shifts larger than the register width are wrapped rather than 4538 // clamped, so we can't just emit "hi >> x". 4539 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 4540 SDValue HiForBigShift = 4541 Opc == ISD::SRA 4542 ? DAG.getNode(Opc, dl, VT, ShOpHi, 4543 DAG.getConstant(VTBits - 1, dl, MVT::i64)) 4544 : DAG.getConstant(0, dl, VT); 4545 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 4546 HiForNormalShift, CCVal, Cmp); 4547 4548 SDValue Ops[2] = { Lo, Hi }; 4549 return DAG.getMergeValues(Ops, dl); 4550 } 4551 4552 4553 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 4554 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 4555 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op, 4556 SelectionDAG &DAG) const { 4557 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 4558 EVT VT = Op.getValueType(); 4559 unsigned VTBits = VT.getSizeInBits(); 4560 SDLoc dl(Op); 4561 SDValue ShOpLo = Op.getOperand(0); 4562 SDValue ShOpHi = Op.getOperand(1); 4563 SDValue ShAmt = Op.getOperand(2); 4564 4565 assert(Op.getOpcode() == ISD::SHL_PARTS); 4566 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 4567 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 4568 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 4569 4570 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which 4571 // is "undef". We wanted 0, so CSEL it directly. 4572 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 4573 ISD::SETEQ, dl, DAG); 4574 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 4575 LoBitsForHi = 4576 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 4577 LoBitsForHi, CCVal, Cmp); 4578 4579 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 4580 DAG.getConstant(VTBits, dl, MVT::i64)); 4581 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 4582 SDValue HiForNormalShift = 4583 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi); 4584 4585 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 4586 4587 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 4588 dl, DAG); 4589 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 4590 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 4591 HiForNormalShift, CCVal, Cmp); 4592 4593 // AArch64 shifts of larger than register sizes are wrapped rather than 4594 // clamped, so we can't just emit "lo << a" if a is too big. 4595 SDValue LoForBigShift = DAG.getConstant(0, dl, VT); 4596 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 4597 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 4598 LoForNormalShift, CCVal, Cmp); 4599 4600 SDValue Ops[2] = { Lo, Hi }; 4601 return DAG.getMergeValues(Ops, dl); 4602 } 4603 4604 bool AArch64TargetLowering::isOffsetFoldingLegal( 4605 const GlobalAddressSDNode *GA) const { 4606 // The AArch64 target doesn't support folding offsets into global addresses. 4607 return false; 4608 } 4609 4610 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const { 4611 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases. 4612 // FIXME: We should be able to handle f128 as well with a clever lowering. 4613 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32)) 4614 return true; 4615 4616 if (VT == MVT::f64) 4617 return AArch64_AM::getFP64Imm(Imm) != -1; 4618 else if (VT == MVT::f32) 4619 return AArch64_AM::getFP32Imm(Imm) != -1; 4620 return false; 4621 } 4622 4623 //===----------------------------------------------------------------------===// 4624 // AArch64 Optimization Hooks 4625 //===----------------------------------------------------------------------===// 4626 4627 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode, 4628 SDValue Operand, SelectionDAG &DAG, 4629 int &ExtraSteps) { 4630 EVT VT = Operand.getValueType(); 4631 if (ST->hasNEON() && 4632 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 || 4633 VT == MVT::f32 || VT == MVT::v1f32 || 4634 VT == MVT::v2f32 || VT == MVT::v4f32)) { 4635 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified) 4636 // For the reciprocal estimates, convergence is quadratic, so the number 4637 // of digits is doubled after each iteration. In ARMv8, the accuracy of 4638 // the initial estimate is 2^-8. Thus the number of extra steps to refine 4639 // the result for float (23 mantissa bits) is 2 and for double (52 4640 // mantissa bits) is 3. 4641 ExtraSteps = VT == MVT::f64 ? 3 : 2; 4642 4643 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand); 4644 } 4645 4646 return SDValue(); 4647 } 4648 4649 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand, 4650 SelectionDAG &DAG, int Enabled, 4651 int &ExtraSteps, 4652 bool &UseOneConst, 4653 bool Reciprocal) const { 4654 if (Enabled == ReciprocalEstimate::Enabled || 4655 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt())) 4656 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand, 4657 DAG, ExtraSteps)) { 4658 SDLoc DL(Operand); 4659 EVT VT = Operand.getValueType(); 4660 4661 SDNodeFlags Flags; 4662 Flags.setUnsafeAlgebra(true); 4663 4664 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2) 4665 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N) 4666 for (int i = ExtraSteps; i > 0; --i) { 4667 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate, 4668 &Flags); 4669 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, &Flags); 4670 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, &Flags); 4671 } 4672 4673 if (!Reciprocal) { 4674 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 4675 VT); 4676 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 4677 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ); 4678 4679 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, &Flags); 4680 // Correct the result if the operand is 0.0. 4681 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, 4682 VT, Eq, Operand, Estimate); 4683 } 4684 4685 ExtraSteps = 0; 4686 return Estimate; 4687 } 4688 4689 return SDValue(); 4690 } 4691 4692 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand, 4693 SelectionDAG &DAG, int Enabled, 4694 int &ExtraSteps) const { 4695 if (Enabled == ReciprocalEstimate::Enabled) 4696 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand, 4697 DAG, ExtraSteps)) { 4698 SDLoc DL(Operand); 4699 EVT VT = Operand.getValueType(); 4700 4701 SDNodeFlags Flags; 4702 Flags.setUnsafeAlgebra(true); 4703 4704 // Newton reciprocal iteration: E * (2 - X * E) 4705 // AArch64 reciprocal iteration instruction: (2 - M * N) 4706 for (int i = ExtraSteps; i > 0; --i) { 4707 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand, 4708 Estimate, &Flags); 4709 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, &Flags); 4710 } 4711 4712 ExtraSteps = 0; 4713 return Estimate; 4714 } 4715 4716 return SDValue(); 4717 } 4718 4719 //===----------------------------------------------------------------------===// 4720 // AArch64 Inline Assembly Support 4721 //===----------------------------------------------------------------------===// 4722 4723 // Table of Constraints 4724 // TODO: This is the current set of constraints supported by ARM for the 4725 // compiler, not all of them may make sense, e.g. S may be difficult to support. 4726 // 4727 // r - A general register 4728 // w - An FP/SIMD register of some size in the range v0-v31 4729 // x - An FP/SIMD register of some size in the range v0-v15 4730 // I - Constant that can be used with an ADD instruction 4731 // J - Constant that can be used with a SUB instruction 4732 // K - Constant that can be used with a 32-bit logical instruction 4733 // L - Constant that can be used with a 64-bit logical instruction 4734 // M - Constant that can be used as a 32-bit MOV immediate 4735 // N - Constant that can be used as a 64-bit MOV immediate 4736 // Q - A memory reference with base register and no offset 4737 // S - A symbolic address 4738 // Y - Floating point constant zero 4739 // Z - Integer constant zero 4740 // 4741 // Note that general register operands will be output using their 64-bit x 4742 // register name, whatever the size of the variable, unless the asm operand 4743 // is prefixed by the %w modifier. Floating-point and SIMD register operands 4744 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or 4745 // %q modifier. 4746 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 4747 // At this point, we have to lower this constraint to something else, so we 4748 // lower it to an "r" or "w". However, by doing this we will force the result 4749 // to be in register, while the X constraint is much more permissive. 4750 // 4751 // Although we are correct (we are free to emit anything, without 4752 // constraints), we might break use cases that would expect us to be more 4753 // efficient and emit something else. 4754 if (!Subtarget->hasFPARMv8()) 4755 return "r"; 4756 4757 if (ConstraintVT.isFloatingPoint()) 4758 return "w"; 4759 4760 if (ConstraintVT.isVector() && 4761 (ConstraintVT.getSizeInBits() == 64 || 4762 ConstraintVT.getSizeInBits() == 128)) 4763 return "w"; 4764 4765 return "r"; 4766 } 4767 4768 /// getConstraintType - Given a constraint letter, return the type of 4769 /// constraint it is for this target. 4770 AArch64TargetLowering::ConstraintType 4771 AArch64TargetLowering::getConstraintType(StringRef Constraint) const { 4772 if (Constraint.size() == 1) { 4773 switch (Constraint[0]) { 4774 default: 4775 break; 4776 case 'z': 4777 return C_Other; 4778 case 'x': 4779 case 'w': 4780 return C_RegisterClass; 4781 // An address with a single base register. Due to the way we 4782 // currently handle addresses it is the same as 'r'. 4783 case 'Q': 4784 return C_Memory; 4785 } 4786 } 4787 return TargetLowering::getConstraintType(Constraint); 4788 } 4789 4790 /// Examine constraint type and operand type and determine a weight value. 4791 /// This object must already have been set up with the operand type 4792 /// and the current alternative constraint selected. 4793 TargetLowering::ConstraintWeight 4794 AArch64TargetLowering::getSingleConstraintMatchWeight( 4795 AsmOperandInfo &info, const char *constraint) const { 4796 ConstraintWeight weight = CW_Invalid; 4797 Value *CallOperandVal = info.CallOperandVal; 4798 // If we don't have a value, we can't do a match, 4799 // but allow it at the lowest weight. 4800 if (!CallOperandVal) 4801 return CW_Default; 4802 Type *type = CallOperandVal->getType(); 4803 // Look at the constraint type. 4804 switch (*constraint) { 4805 default: 4806 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 4807 break; 4808 case 'x': 4809 case 'w': 4810 if (type->isFloatingPointTy() || type->isVectorTy()) 4811 weight = CW_Register; 4812 break; 4813 case 'z': 4814 weight = CW_Constant; 4815 break; 4816 } 4817 return weight; 4818 } 4819 4820 std::pair<unsigned, const TargetRegisterClass *> 4821 AArch64TargetLowering::getRegForInlineAsmConstraint( 4822 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 4823 if (Constraint.size() == 1) { 4824 switch (Constraint[0]) { 4825 case 'r': 4826 if (VT.getSizeInBits() == 64) 4827 return std::make_pair(0U, &AArch64::GPR64commonRegClass); 4828 return std::make_pair(0U, &AArch64::GPR32commonRegClass); 4829 case 'w': 4830 if (VT.getSizeInBits() == 16) 4831 return std::make_pair(0U, &AArch64::FPR16RegClass); 4832 if (VT.getSizeInBits() == 32) 4833 return std::make_pair(0U, &AArch64::FPR32RegClass); 4834 if (VT.getSizeInBits() == 64) 4835 return std::make_pair(0U, &AArch64::FPR64RegClass); 4836 if (VT.getSizeInBits() == 128) 4837 return std::make_pair(0U, &AArch64::FPR128RegClass); 4838 break; 4839 // The instructions that this constraint is designed for can 4840 // only take 128-bit registers so just use that regclass. 4841 case 'x': 4842 if (VT.getSizeInBits() == 128) 4843 return std::make_pair(0U, &AArch64::FPR128_loRegClass); 4844 break; 4845 } 4846 } 4847 if (StringRef("{cc}").equals_lower(Constraint)) 4848 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass); 4849 4850 // Use the default implementation in TargetLowering to convert the register 4851 // constraint into a member of a register class. 4852 std::pair<unsigned, const TargetRegisterClass *> Res; 4853 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 4854 4855 // Not found as a standard register? 4856 if (!Res.second) { 4857 unsigned Size = Constraint.size(); 4858 if ((Size == 4 || Size == 5) && Constraint[0] == '{' && 4859 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') { 4860 int RegNo; 4861 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo); 4862 if (!Failed && RegNo >= 0 && RegNo <= 31) { 4863 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size. 4864 // By default we'll emit v0-v31 for this unless there's a modifier where 4865 // we'll emit the correct register as well. 4866 if (VT != MVT::Other && VT.getSizeInBits() == 64) { 4867 Res.first = AArch64::FPR64RegClass.getRegister(RegNo); 4868 Res.second = &AArch64::FPR64RegClass; 4869 } else { 4870 Res.first = AArch64::FPR128RegClass.getRegister(RegNo); 4871 Res.second = &AArch64::FPR128RegClass; 4872 } 4873 } 4874 } 4875 } 4876 4877 return Res; 4878 } 4879 4880 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 4881 /// vector. If it is invalid, don't add anything to Ops. 4882 void AArch64TargetLowering::LowerAsmOperandForConstraint( 4883 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 4884 SelectionDAG &DAG) const { 4885 SDValue Result; 4886 4887 // Currently only support length 1 constraints. 4888 if (Constraint.length() != 1) 4889 return; 4890 4891 char ConstraintLetter = Constraint[0]; 4892 switch (ConstraintLetter) { 4893 default: 4894 break; 4895 4896 // This set of constraints deal with valid constants for various instructions. 4897 // Validate and return a target constant for them if we can. 4898 case 'z': { 4899 // 'z' maps to xzr or wzr so it needs an input of 0. 4900 if (!isNullConstant(Op)) 4901 return; 4902 4903 if (Op.getValueType() == MVT::i64) 4904 Result = DAG.getRegister(AArch64::XZR, MVT::i64); 4905 else 4906 Result = DAG.getRegister(AArch64::WZR, MVT::i32); 4907 break; 4908 } 4909 4910 case 'I': 4911 case 'J': 4912 case 'K': 4913 case 'L': 4914 case 'M': 4915 case 'N': 4916 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 4917 if (!C) 4918 return; 4919 4920 // Grab the value and do some validation. 4921 uint64_t CVal = C->getZExtValue(); 4922 switch (ConstraintLetter) { 4923 // The I constraint applies only to simple ADD or SUB immediate operands: 4924 // i.e. 0 to 4095 with optional shift by 12 4925 // The J constraint applies only to ADD or SUB immediates that would be 4926 // valid when negated, i.e. if [an add pattern] were to be output as a SUB 4927 // instruction [or vice versa], in other words -1 to -4095 with optional 4928 // left shift by 12. 4929 case 'I': 4930 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal)) 4931 break; 4932 return; 4933 case 'J': { 4934 uint64_t NVal = -C->getSExtValue(); 4935 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) { 4936 CVal = C->getSExtValue(); 4937 break; 4938 } 4939 return; 4940 } 4941 // The K and L constraints apply *only* to logical immediates, including 4942 // what used to be the MOVI alias for ORR (though the MOVI alias has now 4943 // been removed and MOV should be used). So these constraints have to 4944 // distinguish between bit patterns that are valid 32-bit or 64-bit 4945 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but 4946 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice 4947 // versa. 4948 case 'K': 4949 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 4950 break; 4951 return; 4952 case 'L': 4953 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 4954 break; 4955 return; 4956 // The M and N constraints are a superset of K and L respectively, for use 4957 // with the MOV (immediate) alias. As well as the logical immediates they 4958 // also match 32 or 64-bit immediates that can be loaded either using a 4959 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca 4960 // (M) or 64-bit 0x1234000000000000 (N) etc. 4961 // As a note some of this code is liberally stolen from the asm parser. 4962 case 'M': { 4963 if (!isUInt<32>(CVal)) 4964 return; 4965 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 4966 break; 4967 if ((CVal & 0xFFFF) == CVal) 4968 break; 4969 if ((CVal & 0xFFFF0000ULL) == CVal) 4970 break; 4971 uint64_t NCVal = ~(uint32_t)CVal; 4972 if ((NCVal & 0xFFFFULL) == NCVal) 4973 break; 4974 if ((NCVal & 0xFFFF0000ULL) == NCVal) 4975 break; 4976 return; 4977 } 4978 case 'N': { 4979 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 4980 break; 4981 if ((CVal & 0xFFFFULL) == CVal) 4982 break; 4983 if ((CVal & 0xFFFF0000ULL) == CVal) 4984 break; 4985 if ((CVal & 0xFFFF00000000ULL) == CVal) 4986 break; 4987 if ((CVal & 0xFFFF000000000000ULL) == CVal) 4988 break; 4989 uint64_t NCVal = ~CVal; 4990 if ((NCVal & 0xFFFFULL) == NCVal) 4991 break; 4992 if ((NCVal & 0xFFFF0000ULL) == NCVal) 4993 break; 4994 if ((NCVal & 0xFFFF00000000ULL) == NCVal) 4995 break; 4996 if ((NCVal & 0xFFFF000000000000ULL) == NCVal) 4997 break; 4998 return; 4999 } 5000 default: 5001 return; 5002 } 5003 5004 // All assembler immediates are 64-bit integers. 5005 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64); 5006 break; 5007 } 5008 5009 if (Result.getNode()) { 5010 Ops.push_back(Result); 5011 return; 5012 } 5013 5014 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 5015 } 5016 5017 //===----------------------------------------------------------------------===// 5018 // AArch64 Advanced SIMD Support 5019 //===----------------------------------------------------------------------===// 5020 5021 /// WidenVector - Given a value in the V64 register class, produce the 5022 /// equivalent value in the V128 register class. 5023 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) { 5024 EVT VT = V64Reg.getValueType(); 5025 unsigned NarrowSize = VT.getVectorNumElements(); 5026 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 5027 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize); 5028 SDLoc DL(V64Reg); 5029 5030 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy), 5031 V64Reg, DAG.getConstant(0, DL, MVT::i32)); 5032 } 5033 5034 /// getExtFactor - Determine the adjustment factor for the position when 5035 /// generating an "extract from vector registers" instruction. 5036 static unsigned getExtFactor(SDValue &V) { 5037 EVT EltType = V.getValueType().getVectorElementType(); 5038 return EltType.getSizeInBits() / 8; 5039 } 5040 5041 /// NarrowVector - Given a value in the V128 register class, produce the 5042 /// equivalent value in the V64 register class. 5043 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) { 5044 EVT VT = V128Reg.getValueType(); 5045 unsigned WideSize = VT.getVectorNumElements(); 5046 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 5047 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2); 5048 SDLoc DL(V128Reg); 5049 5050 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg); 5051 } 5052 5053 // Gather data to see if the operation can be modelled as a 5054 // shuffle in combination with VEXTs. 5055 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op, 5056 SelectionDAG &DAG) const { 5057 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 5058 SDLoc dl(Op); 5059 EVT VT = Op.getValueType(); 5060 unsigned NumElts = VT.getVectorNumElements(); 5061 5062 struct ShuffleSourceInfo { 5063 SDValue Vec; 5064 unsigned MinElt; 5065 unsigned MaxElt; 5066 5067 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 5068 // be compatible with the shuffle we intend to construct. As a result 5069 // ShuffleVec will be some sliding window into the original Vec. 5070 SDValue ShuffleVec; 5071 5072 // Code should guarantee that element i in Vec starts at element "WindowBase 5073 // + i * WindowScale in ShuffleVec". 5074 int WindowBase; 5075 int WindowScale; 5076 5077 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 5078 ShuffleSourceInfo(SDValue Vec) 5079 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0), 5080 WindowScale(1) {} 5081 }; 5082 5083 // First gather all vectors used as an immediate source for this BUILD_VECTOR 5084 // node. 5085 SmallVector<ShuffleSourceInfo, 2> Sources; 5086 for (unsigned i = 0; i < NumElts; ++i) { 5087 SDValue V = Op.getOperand(i); 5088 if (V.isUndef()) 5089 continue; 5090 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 5091 !isa<ConstantSDNode>(V.getOperand(1))) { 5092 // A shuffle can only come from building a vector from various 5093 // elements of other vectors, provided their indices are constant. 5094 return SDValue(); 5095 } 5096 5097 // Add this element source to the list if it's not already there. 5098 SDValue SourceVec = V.getOperand(0); 5099 auto Source = find(Sources, SourceVec); 5100 if (Source == Sources.end()) 5101 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 5102 5103 // Update the minimum and maximum lane number seen. 5104 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 5105 Source->MinElt = std::min(Source->MinElt, EltNo); 5106 Source->MaxElt = std::max(Source->MaxElt, EltNo); 5107 } 5108 5109 // Currently only do something sane when at most two source vectors 5110 // are involved. 5111 if (Sources.size() > 2) 5112 return SDValue(); 5113 5114 // Find out the smallest element size among result and two sources, and use 5115 // it as element size to build the shuffle_vector. 5116 EVT SmallestEltTy = VT.getVectorElementType(); 5117 for (auto &Source : Sources) { 5118 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 5119 if (SrcEltTy.bitsLT(SmallestEltTy)) { 5120 SmallestEltTy = SrcEltTy; 5121 } 5122 } 5123 unsigned ResMultiplier = 5124 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 5125 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5126 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 5127 5128 // If the source vector is too wide or too narrow, we may nevertheless be able 5129 // to construct a compatible shuffle either by concatenating it with UNDEF or 5130 // extracting a suitable range of elements. 5131 for (auto &Src : Sources) { 5132 EVT SrcVT = Src.ShuffleVec.getValueType(); 5133 5134 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 5135 continue; 5136 5137 // This stage of the search produces a source with the same element type as 5138 // the original, but with a total width matching the BUILD_VECTOR output. 5139 EVT EltVT = SrcVT.getVectorElementType(); 5140 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 5141 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 5142 5143 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 5144 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits()); 5145 // We can pad out the smaller vector for free, so if it's part of a 5146 // shuffle... 5147 Src.ShuffleVec = 5148 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 5149 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 5150 continue; 5151 } 5152 5153 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits()); 5154 5155 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 5156 // Span too large for a VEXT to cope 5157 return SDValue(); 5158 } 5159 5160 if (Src.MinElt >= NumSrcElts) { 5161 // The extraction can just take the second half 5162 Src.ShuffleVec = 5163 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5164 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 5165 Src.WindowBase = -NumSrcElts; 5166 } else if (Src.MaxElt < NumSrcElts) { 5167 // The extraction can just take the first half 5168 Src.ShuffleVec = 5169 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5170 DAG.getConstant(0, dl, MVT::i64)); 5171 } else { 5172 // An actual VEXT is needed 5173 SDValue VEXTSrc1 = 5174 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5175 DAG.getConstant(0, dl, MVT::i64)); 5176 SDValue VEXTSrc2 = 5177 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 5178 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 5179 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1); 5180 5181 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1, 5182 VEXTSrc2, 5183 DAG.getConstant(Imm, dl, MVT::i32)); 5184 Src.WindowBase = -Src.MinElt; 5185 } 5186 } 5187 5188 // Another possible incompatibility occurs from the vector element types. We 5189 // can fix this by bitcasting the source vectors to the same type we intend 5190 // for the shuffle. 5191 for (auto &Src : Sources) { 5192 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 5193 if (SrcEltTy == SmallestEltTy) 5194 continue; 5195 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 5196 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 5197 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 5198 Src.WindowBase *= Src.WindowScale; 5199 } 5200 5201 // Final sanity check before we try to actually produce a shuffle. 5202 DEBUG( 5203 for (auto Src : Sources) 5204 assert(Src.ShuffleVec.getValueType() == ShuffleVT); 5205 ); 5206 5207 // The stars all align, our next step is to produce the mask for the shuffle. 5208 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 5209 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 5210 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 5211 SDValue Entry = Op.getOperand(i); 5212 if (Entry.isUndef()) 5213 continue; 5214 5215 auto Src = find(Sources, Entry.getOperand(0)); 5216 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 5217 5218 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 5219 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 5220 // segment. 5221 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 5222 int BitsDefined = 5223 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits()); 5224 int LanesDefined = BitsDefined / BitsPerShuffleLane; 5225 5226 // This source is expected to fill ResMultiplier lanes of the final shuffle, 5227 // starting at the appropriate offset. 5228 int *LaneMask = &Mask[i * ResMultiplier]; 5229 5230 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 5231 ExtractBase += NumElts * (Src - Sources.begin()); 5232 for (int j = 0; j < LanesDefined; ++j) 5233 LaneMask[j] = ExtractBase + j; 5234 } 5235 5236 // Final check before we try to produce nonsense... 5237 if (!isShuffleMaskLegal(Mask, ShuffleVT)) 5238 return SDValue(); 5239 5240 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 5241 for (unsigned i = 0; i < Sources.size(); ++i) 5242 ShuffleOps[i] = Sources[i].ShuffleVec; 5243 5244 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 5245 ShuffleOps[1], Mask); 5246 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 5247 } 5248 5249 // check if an EXT instruction can handle the shuffle mask when the 5250 // vector sources of the shuffle are the same. 5251 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 5252 unsigned NumElts = VT.getVectorNumElements(); 5253 5254 // Assume that the first shuffle index is not UNDEF. Fail if it is. 5255 if (M[0] < 0) 5256 return false; 5257 5258 Imm = M[0]; 5259 5260 // If this is a VEXT shuffle, the immediate value is the index of the first 5261 // element. The other shuffle indices must be the successive elements after 5262 // the first one. 5263 unsigned ExpectedElt = Imm; 5264 for (unsigned i = 1; i < NumElts; ++i) { 5265 // Increment the expected index. If it wraps around, just follow it 5266 // back to index zero and keep going. 5267 ++ExpectedElt; 5268 if (ExpectedElt == NumElts) 5269 ExpectedElt = 0; 5270 5271 if (M[i] < 0) 5272 continue; // ignore UNDEF indices 5273 if (ExpectedElt != static_cast<unsigned>(M[i])) 5274 return false; 5275 } 5276 5277 return true; 5278 } 5279 5280 // check if an EXT instruction can handle the shuffle mask when the 5281 // vector sources of the shuffle are different. 5282 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT, 5283 unsigned &Imm) { 5284 // Look for the first non-undef element. 5285 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; }); 5286 5287 // Benefit form APInt to handle overflow when calculating expected element. 5288 unsigned NumElts = VT.getVectorNumElements(); 5289 unsigned MaskBits = APInt(32, NumElts * 2).logBase2(); 5290 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1); 5291 // The following shuffle indices must be the successive elements after the 5292 // first real element. 5293 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(), 5294 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;}); 5295 if (FirstWrongElt != M.end()) 5296 return false; 5297 5298 // The index of an EXT is the first element if it is not UNDEF. 5299 // Watch out for the beginning UNDEFs. The EXT index should be the expected 5300 // value of the first element. E.g. 5301 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>. 5302 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>. 5303 // ExpectedElt is the last mask index plus 1. 5304 Imm = ExpectedElt.getZExtValue(); 5305 5306 // There are two difference cases requiring to reverse input vectors. 5307 // For example, for vector <4 x i32> we have the following cases, 5308 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>) 5309 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>) 5310 // For both cases, we finally use mask <5, 6, 7, 0>, which requires 5311 // to reverse two input vectors. 5312 if (Imm < NumElts) 5313 ReverseEXT = true; 5314 else 5315 Imm -= NumElts; 5316 5317 return true; 5318 } 5319 5320 /// isREVMask - Check if a vector shuffle corresponds to a REV 5321 /// instruction with the specified blocksize. (The order of the elements 5322 /// within each block of the vector is reversed.) 5323 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 5324 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) && 5325 "Only possible block sizes for REV are: 16, 32, 64"); 5326 5327 unsigned EltSz = VT.getScalarSizeInBits(); 5328 if (EltSz == 64) 5329 return false; 5330 5331 unsigned NumElts = VT.getVectorNumElements(); 5332 unsigned BlockElts = M[0] + 1; 5333 // If the first shuffle index is UNDEF, be optimistic. 5334 if (M[0] < 0) 5335 BlockElts = BlockSize / EltSz; 5336 5337 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 5338 return false; 5339 5340 for (unsigned i = 0; i < NumElts; ++i) { 5341 if (M[i] < 0) 5342 continue; // ignore UNDEF indices 5343 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts)) 5344 return false; 5345 } 5346 5347 return true; 5348 } 5349 5350 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5351 unsigned NumElts = VT.getVectorNumElements(); 5352 WhichResult = (M[0] == 0 ? 0 : 1); 5353 unsigned Idx = WhichResult * NumElts / 2; 5354 for (unsigned i = 0; i != NumElts; i += 2) { 5355 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 5356 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts)) 5357 return false; 5358 Idx += 1; 5359 } 5360 5361 return true; 5362 } 5363 5364 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5365 unsigned NumElts = VT.getVectorNumElements(); 5366 WhichResult = (M[0] == 0 ? 0 : 1); 5367 for (unsigned i = 0; i != NumElts; ++i) { 5368 if (M[i] < 0) 5369 continue; // ignore UNDEF indices 5370 if ((unsigned)M[i] != 2 * i + WhichResult) 5371 return false; 5372 } 5373 5374 return true; 5375 } 5376 5377 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5378 unsigned NumElts = VT.getVectorNumElements(); 5379 WhichResult = (M[0] == 0 ? 0 : 1); 5380 for (unsigned i = 0; i < NumElts; i += 2) { 5381 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 5382 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult)) 5383 return false; 5384 } 5385 return true; 5386 } 5387 5388 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of 5389 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5390 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 5391 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5392 unsigned NumElts = VT.getVectorNumElements(); 5393 WhichResult = (M[0] == 0 ? 0 : 1); 5394 unsigned Idx = WhichResult * NumElts / 2; 5395 for (unsigned i = 0; i != NumElts; i += 2) { 5396 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 5397 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx)) 5398 return false; 5399 Idx += 1; 5400 } 5401 5402 return true; 5403 } 5404 5405 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of 5406 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5407 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 5408 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5409 unsigned Half = VT.getVectorNumElements() / 2; 5410 WhichResult = (M[0] == 0 ? 0 : 1); 5411 for (unsigned j = 0; j != 2; ++j) { 5412 unsigned Idx = WhichResult; 5413 for (unsigned i = 0; i != Half; ++i) { 5414 int MIdx = M[i + j * Half]; 5415 if (MIdx >= 0 && (unsigned)MIdx != Idx) 5416 return false; 5417 Idx += 2; 5418 } 5419 } 5420 5421 return true; 5422 } 5423 5424 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of 5425 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 5426 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 5427 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 5428 unsigned NumElts = VT.getVectorNumElements(); 5429 WhichResult = (M[0] == 0 ? 0 : 1); 5430 for (unsigned i = 0; i < NumElts; i += 2) { 5431 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 5432 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult)) 5433 return false; 5434 } 5435 return true; 5436 } 5437 5438 static bool isINSMask(ArrayRef<int> M, int NumInputElements, 5439 bool &DstIsLeft, int &Anomaly) { 5440 if (M.size() != static_cast<size_t>(NumInputElements)) 5441 return false; 5442 5443 int NumLHSMatch = 0, NumRHSMatch = 0; 5444 int LastLHSMismatch = -1, LastRHSMismatch = -1; 5445 5446 for (int i = 0; i < NumInputElements; ++i) { 5447 if (M[i] == -1) { 5448 ++NumLHSMatch; 5449 ++NumRHSMatch; 5450 continue; 5451 } 5452 5453 if (M[i] == i) 5454 ++NumLHSMatch; 5455 else 5456 LastLHSMismatch = i; 5457 5458 if (M[i] == i + NumInputElements) 5459 ++NumRHSMatch; 5460 else 5461 LastRHSMismatch = i; 5462 } 5463 5464 if (NumLHSMatch == NumInputElements - 1) { 5465 DstIsLeft = true; 5466 Anomaly = LastLHSMismatch; 5467 return true; 5468 } else if (NumRHSMatch == NumInputElements - 1) { 5469 DstIsLeft = false; 5470 Anomaly = LastRHSMismatch; 5471 return true; 5472 } 5473 5474 return false; 5475 } 5476 5477 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) { 5478 if (VT.getSizeInBits() != 128) 5479 return false; 5480 5481 unsigned NumElts = VT.getVectorNumElements(); 5482 5483 for (int I = 0, E = NumElts / 2; I != E; I++) { 5484 if (Mask[I] != I) 5485 return false; 5486 } 5487 5488 int Offset = NumElts / 2; 5489 for (int I = NumElts / 2, E = NumElts; I != E; I++) { 5490 if (Mask[I] != I + SplitLHS * Offset) 5491 return false; 5492 } 5493 5494 return true; 5495 } 5496 5497 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) { 5498 SDLoc DL(Op); 5499 EVT VT = Op.getValueType(); 5500 SDValue V0 = Op.getOperand(0); 5501 SDValue V1 = Op.getOperand(1); 5502 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask(); 5503 5504 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() || 5505 VT.getVectorElementType() != V1.getValueType().getVectorElementType()) 5506 return SDValue(); 5507 5508 bool SplitV0 = V0.getValueSizeInBits() == 128; 5509 5510 if (!isConcatMask(Mask, VT, SplitV0)) 5511 return SDValue(); 5512 5513 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 5514 VT.getVectorNumElements() / 2); 5515 if (SplitV0) { 5516 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0, 5517 DAG.getConstant(0, DL, MVT::i64)); 5518 } 5519 if (V1.getValueSizeInBits() == 128) { 5520 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1, 5521 DAG.getConstant(0, DL, MVT::i64)); 5522 } 5523 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1); 5524 } 5525 5526 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 5527 /// the specified operations to build the shuffle. 5528 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 5529 SDValue RHS, SelectionDAG &DAG, 5530 const SDLoc &dl) { 5531 unsigned OpNum = (PFEntry >> 26) & 0x0F; 5532 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1); 5533 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1); 5534 5535 enum { 5536 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 5537 OP_VREV, 5538 OP_VDUP0, 5539 OP_VDUP1, 5540 OP_VDUP2, 5541 OP_VDUP3, 5542 OP_VEXT1, 5543 OP_VEXT2, 5544 OP_VEXT3, 5545 OP_VUZPL, // VUZP, left result 5546 OP_VUZPR, // VUZP, right result 5547 OP_VZIPL, // VZIP, left result 5548 OP_VZIPR, // VZIP, right result 5549 OP_VTRNL, // VTRN, left result 5550 OP_VTRNR // VTRN, right result 5551 }; 5552 5553 if (OpNum == OP_COPY) { 5554 if (LHSID == (1 * 9 + 2) * 9 + 3) 5555 return LHS; 5556 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!"); 5557 return RHS; 5558 } 5559 5560 SDValue OpLHS, OpRHS; 5561 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 5562 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 5563 EVT VT = OpLHS.getValueType(); 5564 5565 switch (OpNum) { 5566 default: 5567 llvm_unreachable("Unknown shuffle opcode!"); 5568 case OP_VREV: 5569 // VREV divides the vector in half and swaps within the half. 5570 if (VT.getVectorElementType() == MVT::i32 || 5571 VT.getVectorElementType() == MVT::f32) 5572 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS); 5573 // vrev <4 x i16> -> REV32 5574 if (VT.getVectorElementType() == MVT::i16 || 5575 VT.getVectorElementType() == MVT::f16) 5576 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS); 5577 // vrev <4 x i8> -> REV16 5578 assert(VT.getVectorElementType() == MVT::i8); 5579 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS); 5580 case OP_VDUP0: 5581 case OP_VDUP1: 5582 case OP_VDUP2: 5583 case OP_VDUP3: { 5584 EVT EltTy = VT.getVectorElementType(); 5585 unsigned Opcode; 5586 if (EltTy == MVT::i8) 5587 Opcode = AArch64ISD::DUPLANE8; 5588 else if (EltTy == MVT::i16 || EltTy == MVT::f16) 5589 Opcode = AArch64ISD::DUPLANE16; 5590 else if (EltTy == MVT::i32 || EltTy == MVT::f32) 5591 Opcode = AArch64ISD::DUPLANE32; 5592 else if (EltTy == MVT::i64 || EltTy == MVT::f64) 5593 Opcode = AArch64ISD::DUPLANE64; 5594 else 5595 llvm_unreachable("Invalid vector element type?"); 5596 5597 if (VT.getSizeInBits() == 64) 5598 OpLHS = WidenVector(OpLHS, DAG); 5599 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64); 5600 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane); 5601 } 5602 case OP_VEXT1: 5603 case OP_VEXT2: 5604 case OP_VEXT3: { 5605 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS); 5606 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS, 5607 DAG.getConstant(Imm, dl, MVT::i32)); 5608 } 5609 case OP_VUZPL: 5610 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, 5611 OpRHS); 5612 case OP_VUZPR: 5613 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, 5614 OpRHS); 5615 case OP_VZIPL: 5616 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, 5617 OpRHS); 5618 case OP_VZIPR: 5619 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, 5620 OpRHS); 5621 case OP_VTRNL: 5622 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, 5623 OpRHS); 5624 case OP_VTRNR: 5625 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, 5626 OpRHS); 5627 } 5628 } 5629 5630 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask, 5631 SelectionDAG &DAG) { 5632 // Check to see if we can use the TBL instruction. 5633 SDValue V1 = Op.getOperand(0); 5634 SDValue V2 = Op.getOperand(1); 5635 SDLoc DL(Op); 5636 5637 EVT EltVT = Op.getValueType().getVectorElementType(); 5638 unsigned BytesPerElt = EltVT.getSizeInBits() / 8; 5639 5640 SmallVector<SDValue, 8> TBLMask; 5641 for (int Val : ShuffleMask) { 5642 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) { 5643 unsigned Offset = Byte + Val * BytesPerElt; 5644 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32)); 5645 } 5646 } 5647 5648 MVT IndexVT = MVT::v8i8; 5649 unsigned IndexLen = 8; 5650 if (Op.getValueSizeInBits() == 128) { 5651 IndexVT = MVT::v16i8; 5652 IndexLen = 16; 5653 } 5654 5655 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1); 5656 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2); 5657 5658 SDValue Shuffle; 5659 if (V2.getNode()->isUndef()) { 5660 if (IndexLen == 8) 5661 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst); 5662 Shuffle = DAG.getNode( 5663 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 5664 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 5665 DAG.getBuildVector(IndexVT, DL, 5666 makeArrayRef(TBLMask.data(), IndexLen))); 5667 } else { 5668 if (IndexLen == 8) { 5669 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst); 5670 Shuffle = DAG.getNode( 5671 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 5672 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 5673 DAG.getBuildVector(IndexVT, DL, 5674 makeArrayRef(TBLMask.data(), IndexLen))); 5675 } else { 5676 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we 5677 // cannot currently represent the register constraints on the input 5678 // table registers. 5679 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst, 5680 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0], 5681 // IndexLen)); 5682 Shuffle = DAG.getNode( 5683 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 5684 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst, 5685 V2Cst, DAG.getBuildVector(IndexVT, DL, 5686 makeArrayRef(TBLMask.data(), IndexLen))); 5687 } 5688 } 5689 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle); 5690 } 5691 5692 static unsigned getDUPLANEOp(EVT EltType) { 5693 if (EltType == MVT::i8) 5694 return AArch64ISD::DUPLANE8; 5695 if (EltType == MVT::i16 || EltType == MVT::f16) 5696 return AArch64ISD::DUPLANE16; 5697 if (EltType == MVT::i32 || EltType == MVT::f32) 5698 return AArch64ISD::DUPLANE32; 5699 if (EltType == MVT::i64 || EltType == MVT::f64) 5700 return AArch64ISD::DUPLANE64; 5701 5702 llvm_unreachable("Invalid vector element type?"); 5703 } 5704 5705 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 5706 SelectionDAG &DAG) const { 5707 SDLoc dl(Op); 5708 EVT VT = Op.getValueType(); 5709 5710 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 5711 5712 // Convert shuffles that are directly supported on NEON to target-specific 5713 // DAG nodes, instead of keeping them as shuffles and matching them again 5714 // during code selection. This is more efficient and avoids the possibility 5715 // of inconsistencies between legalization and selection. 5716 ArrayRef<int> ShuffleMask = SVN->getMask(); 5717 5718 SDValue V1 = Op.getOperand(0); 5719 SDValue V2 = Op.getOperand(1); 5720 5721 if (SVN->isSplat()) { 5722 int Lane = SVN->getSplatIndex(); 5723 // If this is undef splat, generate it via "just" vdup, if possible. 5724 if (Lane == -1) 5725 Lane = 0; 5726 5727 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) 5728 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(), 5729 V1.getOperand(0)); 5730 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non- 5731 // constant. If so, we can just reference the lane's definition directly. 5732 if (V1.getOpcode() == ISD::BUILD_VECTOR && 5733 !isa<ConstantSDNode>(V1.getOperand(Lane))) 5734 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane)); 5735 5736 // Otherwise, duplicate from the lane of the input vector. 5737 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType()); 5738 5739 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated 5740 // to make a vector of the same size as this SHUFFLE. We can ignore the 5741 // extract entirely, and canonicalise the concat using WidenVector. 5742 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) { 5743 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue(); 5744 V1 = V1.getOperand(0); 5745 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) { 5746 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2; 5747 Lane -= Idx * VT.getVectorNumElements() / 2; 5748 V1 = WidenVector(V1.getOperand(Idx), DAG); 5749 } else if (VT.getSizeInBits() == 64) 5750 V1 = WidenVector(V1, DAG); 5751 5752 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64)); 5753 } 5754 5755 if (isREVMask(ShuffleMask, VT, 64)) 5756 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2); 5757 if (isREVMask(ShuffleMask, VT, 32)) 5758 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2); 5759 if (isREVMask(ShuffleMask, VT, 16)) 5760 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2); 5761 5762 bool ReverseEXT = false; 5763 unsigned Imm; 5764 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) { 5765 if (ReverseEXT) 5766 std::swap(V1, V2); 5767 Imm *= getExtFactor(V1); 5768 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2, 5769 DAG.getConstant(Imm, dl, MVT::i32)); 5770 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) { 5771 Imm *= getExtFactor(V1); 5772 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1, 5773 DAG.getConstant(Imm, dl, MVT::i32)); 5774 } 5775 5776 unsigned WhichResult; 5777 if (isZIPMask(ShuffleMask, VT, WhichResult)) { 5778 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 5779 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 5780 } 5781 if (isUZPMask(ShuffleMask, VT, WhichResult)) { 5782 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 5783 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 5784 } 5785 if (isTRNMask(ShuffleMask, VT, WhichResult)) { 5786 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 5787 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 5788 } 5789 5790 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 5791 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 5792 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 5793 } 5794 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 5795 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 5796 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 5797 } 5798 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 5799 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 5800 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 5801 } 5802 5803 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG)) 5804 return Concat; 5805 5806 bool DstIsLeft; 5807 int Anomaly; 5808 int NumInputElements = V1.getValueType().getVectorNumElements(); 5809 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) { 5810 SDValue DstVec = DstIsLeft ? V1 : V2; 5811 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64); 5812 5813 SDValue SrcVec = V1; 5814 int SrcLane = ShuffleMask[Anomaly]; 5815 if (SrcLane >= NumInputElements) { 5816 SrcVec = V2; 5817 SrcLane -= VT.getVectorNumElements(); 5818 } 5819 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64); 5820 5821 EVT ScalarVT = VT.getVectorElementType(); 5822 5823 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger()) 5824 ScalarVT = MVT::i32; 5825 5826 return DAG.getNode( 5827 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec, 5828 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV), 5829 DstLaneV); 5830 } 5831 5832 // If the shuffle is not directly supported and it has 4 elements, use 5833 // the PerfectShuffle-generated table to synthesize it from other shuffles. 5834 unsigned NumElts = VT.getVectorNumElements(); 5835 if (NumElts == 4) { 5836 unsigned PFIndexes[4]; 5837 for (unsigned i = 0; i != 4; ++i) { 5838 if (ShuffleMask[i] < 0) 5839 PFIndexes[i] = 8; 5840 else 5841 PFIndexes[i] = ShuffleMask[i]; 5842 } 5843 5844 // Compute the index in the perfect shuffle table. 5845 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 5846 PFIndexes[2] * 9 + PFIndexes[3]; 5847 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 5848 unsigned Cost = (PFEntry >> 30); 5849 5850 if (Cost <= 4) 5851 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 5852 } 5853 5854 return GenerateTBL(Op, ShuffleMask, DAG); 5855 } 5856 5857 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits, 5858 APInt &UndefBits) { 5859 EVT VT = BVN->getValueType(0); 5860 APInt SplatBits, SplatUndef; 5861 unsigned SplatBitSize; 5862 bool HasAnyUndefs; 5863 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 5864 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize; 5865 5866 for (unsigned i = 0; i < NumSplats; ++i) { 5867 CnstBits <<= SplatBitSize; 5868 UndefBits <<= SplatBitSize; 5869 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits()); 5870 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits()); 5871 } 5872 5873 return true; 5874 } 5875 5876 return false; 5877 } 5878 5879 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op, 5880 SelectionDAG &DAG) const { 5881 BuildVectorSDNode *BVN = 5882 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode()); 5883 SDValue LHS = Op.getOperand(0); 5884 SDLoc dl(Op); 5885 EVT VT = Op.getValueType(); 5886 5887 if (!BVN) 5888 return Op; 5889 5890 APInt CnstBits(VT.getSizeInBits(), 0); 5891 APInt UndefBits(VT.getSizeInBits(), 0); 5892 if (resolveBuildVector(BVN, CnstBits, UndefBits)) { 5893 // We only have BIC vector immediate instruction, which is and-not. 5894 CnstBits = ~CnstBits; 5895 5896 // We make use of a little bit of goto ickiness in order to avoid having to 5897 // duplicate the immediate matching logic for the undef toggled case. 5898 bool SecondTry = false; 5899 AttemptModImm: 5900 5901 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) { 5902 CnstBits = CnstBits.zextOrTrunc(64); 5903 uint64_t CnstVal = CnstBits.getZExtValue(); 5904 5905 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 5906 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 5907 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 5908 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 5909 DAG.getConstant(CnstVal, dl, MVT::i32), 5910 DAG.getConstant(0, dl, MVT::i32)); 5911 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 5912 } 5913 5914 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 5915 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 5916 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 5917 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 5918 DAG.getConstant(CnstVal, dl, MVT::i32), 5919 DAG.getConstant(8, dl, MVT::i32)); 5920 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 5921 } 5922 5923 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 5924 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 5925 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 5926 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 5927 DAG.getConstant(CnstVal, dl, MVT::i32), 5928 DAG.getConstant(16, dl, MVT::i32)); 5929 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 5930 } 5931 5932 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 5933 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 5934 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 5935 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 5936 DAG.getConstant(CnstVal, dl, MVT::i32), 5937 DAG.getConstant(24, dl, MVT::i32)); 5938 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 5939 } 5940 5941 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 5942 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 5943 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 5944 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 5945 DAG.getConstant(CnstVal, dl, MVT::i32), 5946 DAG.getConstant(0, dl, MVT::i32)); 5947 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 5948 } 5949 5950 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 5951 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 5952 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 5953 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS, 5954 DAG.getConstant(CnstVal, dl, MVT::i32), 5955 DAG.getConstant(8, dl, MVT::i32)); 5956 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 5957 } 5958 } 5959 5960 if (SecondTry) 5961 goto FailedModImm; 5962 SecondTry = true; 5963 CnstBits = ~UndefBits; 5964 goto AttemptModImm; 5965 } 5966 5967 // We can always fall back to a non-immediate AND. 5968 FailedModImm: 5969 return Op; 5970 } 5971 5972 // Specialized code to quickly find if PotentialBVec is a BuildVector that 5973 // consists of only the same constant int value, returned in reference arg 5974 // ConstVal 5975 static bool isAllConstantBuildVector(const SDValue &PotentialBVec, 5976 uint64_t &ConstVal) { 5977 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec); 5978 if (!Bvec) 5979 return false; 5980 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0)); 5981 if (!FirstElt) 5982 return false; 5983 EVT VT = Bvec->getValueType(0); 5984 unsigned NumElts = VT.getVectorNumElements(); 5985 for (unsigned i = 1; i < NumElts; ++i) 5986 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt) 5987 return false; 5988 ConstVal = FirstElt->getZExtValue(); 5989 return true; 5990 } 5991 5992 static unsigned getIntrinsicID(const SDNode *N) { 5993 unsigned Opcode = N->getOpcode(); 5994 switch (Opcode) { 5995 default: 5996 return Intrinsic::not_intrinsic; 5997 case ISD::INTRINSIC_WO_CHAIN: { 5998 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 5999 if (IID < Intrinsic::num_intrinsics) 6000 return IID; 6001 return Intrinsic::not_intrinsic; 6002 } 6003 } 6004 } 6005 6006 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)), 6007 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a 6008 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2. 6009 // Also, logical shift right -> sri, with the same structure. 6010 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) { 6011 EVT VT = N->getValueType(0); 6012 6013 if (!VT.isVector()) 6014 return SDValue(); 6015 6016 SDLoc DL(N); 6017 6018 // Is the first op an AND? 6019 const SDValue And = N->getOperand(0); 6020 if (And.getOpcode() != ISD::AND) 6021 return SDValue(); 6022 6023 // Is the second op an shl or lshr? 6024 SDValue Shift = N->getOperand(1); 6025 // This will have been turned into: AArch64ISD::VSHL vector, #shift 6026 // or AArch64ISD::VLSHR vector, #shift 6027 unsigned ShiftOpc = Shift.getOpcode(); 6028 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR)) 6029 return SDValue(); 6030 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR; 6031 6032 // Is the shift amount constant? 6033 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 6034 if (!C2node) 6035 return SDValue(); 6036 6037 // Is the and mask vector all constant? 6038 uint64_t C1; 6039 if (!isAllConstantBuildVector(And.getOperand(1), C1)) 6040 return SDValue(); 6041 6042 // Is C1 == ~C2, taking into account how much one can shift elements of a 6043 // particular size? 6044 uint64_t C2 = C2node->getZExtValue(); 6045 unsigned ElemSizeInBits = VT.getScalarSizeInBits(); 6046 if (C2 > ElemSizeInBits) 6047 return SDValue(); 6048 unsigned ElemMask = (1 << ElemSizeInBits) - 1; 6049 if ((C1 & ElemMask) != (~C2 & ElemMask)) 6050 return SDValue(); 6051 6052 SDValue X = And.getOperand(0); 6053 SDValue Y = Shift.getOperand(0); 6054 6055 unsigned Intrin = 6056 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli; 6057 SDValue ResultSLI = 6058 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 6059 DAG.getConstant(Intrin, DL, MVT::i32), X, Y, 6060 Shift.getOperand(1)); 6061 6062 DEBUG(dbgs() << "aarch64-lower: transformed: \n"); 6063 DEBUG(N->dump(&DAG)); 6064 DEBUG(dbgs() << "into: \n"); 6065 DEBUG(ResultSLI->dump(&DAG)); 6066 6067 ++NumShiftInserts; 6068 return ResultSLI; 6069 } 6070 6071 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op, 6072 SelectionDAG &DAG) const { 6073 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2)) 6074 if (EnableAArch64SlrGeneration) { 6075 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG)) 6076 return Res; 6077 } 6078 6079 BuildVectorSDNode *BVN = 6080 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode()); 6081 SDValue LHS = Op.getOperand(1); 6082 SDLoc dl(Op); 6083 EVT VT = Op.getValueType(); 6084 6085 // OR commutes, so try swapping the operands. 6086 if (!BVN) { 6087 LHS = Op.getOperand(0); 6088 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode()); 6089 } 6090 if (!BVN) 6091 return Op; 6092 6093 APInt CnstBits(VT.getSizeInBits(), 0); 6094 APInt UndefBits(VT.getSizeInBits(), 0); 6095 if (resolveBuildVector(BVN, CnstBits, UndefBits)) { 6096 // We make use of a little bit of goto ickiness in order to avoid having to 6097 // duplicate the immediate matching logic for the undef toggled case. 6098 bool SecondTry = false; 6099 AttemptModImm: 6100 6101 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) { 6102 CnstBits = CnstBits.zextOrTrunc(64); 6103 uint64_t CnstVal = CnstBits.getZExtValue(); 6104 6105 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 6106 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 6107 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6108 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6109 DAG.getConstant(CnstVal, dl, MVT::i32), 6110 DAG.getConstant(0, dl, MVT::i32)); 6111 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6112 } 6113 6114 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 6115 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 6116 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6117 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6118 DAG.getConstant(CnstVal, dl, MVT::i32), 6119 DAG.getConstant(8, dl, MVT::i32)); 6120 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6121 } 6122 6123 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 6124 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 6125 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6126 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6127 DAG.getConstant(CnstVal, dl, MVT::i32), 6128 DAG.getConstant(16, dl, MVT::i32)); 6129 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6130 } 6131 6132 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 6133 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 6134 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6135 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6136 DAG.getConstant(CnstVal, dl, MVT::i32), 6137 DAG.getConstant(24, dl, MVT::i32)); 6138 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6139 } 6140 6141 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 6142 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 6143 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6144 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6145 DAG.getConstant(CnstVal, dl, MVT::i32), 6146 DAG.getConstant(0, dl, MVT::i32)); 6147 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6148 } 6149 6150 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 6151 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 6152 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6153 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS, 6154 DAG.getConstant(CnstVal, dl, MVT::i32), 6155 DAG.getConstant(8, dl, MVT::i32)); 6156 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6157 } 6158 } 6159 6160 if (SecondTry) 6161 goto FailedModImm; 6162 SecondTry = true; 6163 CnstBits = UndefBits; 6164 goto AttemptModImm; 6165 } 6166 6167 // We can always fall back to a non-immediate OR. 6168 FailedModImm: 6169 return Op; 6170 } 6171 6172 // Normalize the operands of BUILD_VECTOR. The value of constant operands will 6173 // be truncated to fit element width. 6174 static SDValue NormalizeBuildVector(SDValue Op, 6175 SelectionDAG &DAG) { 6176 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 6177 SDLoc dl(Op); 6178 EVT VT = Op.getValueType(); 6179 EVT EltTy= VT.getVectorElementType(); 6180 6181 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16) 6182 return Op; 6183 6184 SmallVector<SDValue, 16> Ops; 6185 for (SDValue Lane : Op->ops()) { 6186 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) { 6187 APInt LowBits(EltTy.getSizeInBits(), 6188 CstLane->getZExtValue()); 6189 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32); 6190 } 6191 Ops.push_back(Lane); 6192 } 6193 return DAG.getBuildVector(VT, dl, Ops); 6194 } 6195 6196 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op, 6197 SelectionDAG &DAG) const { 6198 SDLoc dl(Op); 6199 EVT VT = Op.getValueType(); 6200 Op = NormalizeBuildVector(Op, DAG); 6201 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 6202 6203 APInt CnstBits(VT.getSizeInBits(), 0); 6204 APInt UndefBits(VT.getSizeInBits(), 0); 6205 if (resolveBuildVector(BVN, CnstBits, UndefBits)) { 6206 // We make use of a little bit of goto ickiness in order to avoid having to 6207 // duplicate the immediate matching logic for the undef toggled case. 6208 bool SecondTry = false; 6209 AttemptModImm: 6210 6211 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) { 6212 CnstBits = CnstBits.zextOrTrunc(64); 6213 uint64_t CnstVal = CnstBits.getZExtValue(); 6214 6215 // Certain magic vector constants (used to express things like NOT 6216 // and NEG) are passed through unmodified. This allows codegen patterns 6217 // for these operations to match. Special-purpose patterns will lower 6218 // these immediates to MOVIs if it proves necessary. 6219 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL)) 6220 return Op; 6221 6222 // The many faces of MOVI... 6223 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) { 6224 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal); 6225 if (VT.getSizeInBits() == 128) { 6226 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64, 6227 DAG.getConstant(CnstVal, dl, MVT::i32)); 6228 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6229 } 6230 6231 // Support the V64 version via subregister insertion. 6232 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64, 6233 DAG.getConstant(CnstVal, dl, MVT::i32)); 6234 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6235 } 6236 6237 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 6238 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 6239 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6240 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6241 DAG.getConstant(CnstVal, dl, MVT::i32), 6242 DAG.getConstant(0, dl, MVT::i32)); 6243 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6244 } 6245 6246 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 6247 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 6248 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6249 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6250 DAG.getConstant(CnstVal, dl, MVT::i32), 6251 DAG.getConstant(8, dl, MVT::i32)); 6252 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6253 } 6254 6255 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 6256 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 6257 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6258 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6259 DAG.getConstant(CnstVal, dl, MVT::i32), 6260 DAG.getConstant(16, dl, MVT::i32)); 6261 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6262 } 6263 6264 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 6265 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 6266 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6267 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6268 DAG.getConstant(CnstVal, dl, MVT::i32), 6269 DAG.getConstant(24, dl, MVT::i32)); 6270 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6271 } 6272 6273 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 6274 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 6275 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6276 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6277 DAG.getConstant(CnstVal, dl, MVT::i32), 6278 DAG.getConstant(0, dl, MVT::i32)); 6279 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6280 } 6281 6282 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 6283 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 6284 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6285 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy, 6286 DAG.getConstant(CnstVal, dl, MVT::i32), 6287 DAG.getConstant(8, dl, MVT::i32)); 6288 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6289 } 6290 6291 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) { 6292 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal); 6293 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6294 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy, 6295 DAG.getConstant(CnstVal, dl, MVT::i32), 6296 DAG.getConstant(264, dl, MVT::i32)); 6297 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6298 } 6299 6300 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) { 6301 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal); 6302 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6303 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy, 6304 DAG.getConstant(CnstVal, dl, MVT::i32), 6305 DAG.getConstant(272, dl, MVT::i32)); 6306 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6307 } 6308 6309 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) { 6310 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal); 6311 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8; 6312 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy, 6313 DAG.getConstant(CnstVal, dl, MVT::i32)); 6314 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6315 } 6316 6317 // The few faces of FMOV... 6318 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) { 6319 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal); 6320 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32; 6321 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy, 6322 DAG.getConstant(CnstVal, dl, MVT::i32)); 6323 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6324 } 6325 6326 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) && 6327 VT.getSizeInBits() == 128) { 6328 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal); 6329 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64, 6330 DAG.getConstant(CnstVal, dl, MVT::i32)); 6331 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6332 } 6333 6334 // The many faces of MVNI... 6335 CnstVal = ~CnstVal; 6336 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) { 6337 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal); 6338 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6339 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6340 DAG.getConstant(CnstVal, dl, MVT::i32), 6341 DAG.getConstant(0, dl, MVT::i32)); 6342 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6343 } 6344 6345 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) { 6346 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal); 6347 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6348 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6349 DAG.getConstant(CnstVal, dl, MVT::i32), 6350 DAG.getConstant(8, dl, MVT::i32)); 6351 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6352 } 6353 6354 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) { 6355 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal); 6356 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6357 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6358 DAG.getConstant(CnstVal, dl, MVT::i32), 6359 DAG.getConstant(16, dl, MVT::i32)); 6360 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6361 } 6362 6363 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) { 6364 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal); 6365 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6366 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6367 DAG.getConstant(CnstVal, dl, MVT::i32), 6368 DAG.getConstant(24, dl, MVT::i32)); 6369 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6370 } 6371 6372 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) { 6373 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal); 6374 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6375 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6376 DAG.getConstant(CnstVal, dl, MVT::i32), 6377 DAG.getConstant(0, dl, MVT::i32)); 6378 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6379 } 6380 6381 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) { 6382 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal); 6383 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6384 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy, 6385 DAG.getConstant(CnstVal, dl, MVT::i32), 6386 DAG.getConstant(8, dl, MVT::i32)); 6387 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6388 } 6389 6390 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) { 6391 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal); 6392 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6393 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy, 6394 DAG.getConstant(CnstVal, dl, MVT::i32), 6395 DAG.getConstant(264, dl, MVT::i32)); 6396 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6397 } 6398 6399 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) { 6400 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal); 6401 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6402 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy, 6403 DAG.getConstant(CnstVal, dl, MVT::i32), 6404 DAG.getConstant(272, dl, MVT::i32)); 6405 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6406 } 6407 } 6408 6409 if (SecondTry) 6410 goto FailedModImm; 6411 SecondTry = true; 6412 CnstBits = UndefBits; 6413 goto AttemptModImm; 6414 } 6415 FailedModImm: 6416 6417 // Scan through the operands to find some interesting properties we can 6418 // exploit: 6419 // 1) If only one value is used, we can use a DUP, or 6420 // 2) if only the low element is not undef, we can just insert that, or 6421 // 3) if only one constant value is used (w/ some non-constant lanes), 6422 // we can splat the constant value into the whole vector then fill 6423 // in the non-constant lanes. 6424 // 4) FIXME: If different constant values are used, but we can intelligently 6425 // select the values we'll be overwriting for the non-constant 6426 // lanes such that we can directly materialize the vector 6427 // some other way (MOVI, e.g.), we can be sneaky. 6428 unsigned NumElts = VT.getVectorNumElements(); 6429 bool isOnlyLowElement = true; 6430 bool usesOnlyOneValue = true; 6431 bool usesOnlyOneConstantValue = true; 6432 bool isConstant = true; 6433 unsigned NumConstantLanes = 0; 6434 SDValue Value; 6435 SDValue ConstantValue; 6436 for (unsigned i = 0; i < NumElts; ++i) { 6437 SDValue V = Op.getOperand(i); 6438 if (V.isUndef()) 6439 continue; 6440 if (i > 0) 6441 isOnlyLowElement = false; 6442 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 6443 isConstant = false; 6444 6445 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) { 6446 ++NumConstantLanes; 6447 if (!ConstantValue.getNode()) 6448 ConstantValue = V; 6449 else if (ConstantValue != V) 6450 usesOnlyOneConstantValue = false; 6451 } 6452 6453 if (!Value.getNode()) 6454 Value = V; 6455 else if (V != Value) 6456 usesOnlyOneValue = false; 6457 } 6458 6459 if (!Value.getNode()) 6460 return DAG.getUNDEF(VT); 6461 6462 if (isOnlyLowElement) 6463 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 6464 6465 // Use DUP for non-constant splats. For f32 constant splats, reduce to 6466 // i32 and try again. 6467 if (usesOnlyOneValue) { 6468 if (!isConstant) { 6469 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 6470 Value.getValueType() != VT) 6471 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value); 6472 6473 // This is actually a DUPLANExx operation, which keeps everything vectory. 6474 6475 // DUPLANE works on 128-bit vectors, widen it if necessary. 6476 SDValue Lane = Value.getOperand(1); 6477 Value = Value.getOperand(0); 6478 if (Value.getValueSizeInBits() == 64) 6479 Value = WidenVector(Value, DAG); 6480 6481 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType()); 6482 return DAG.getNode(Opcode, dl, VT, Value, Lane); 6483 } 6484 6485 if (VT.getVectorElementType().isFloatingPoint()) { 6486 SmallVector<SDValue, 8> Ops; 6487 EVT EltTy = VT.getVectorElementType(); 6488 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) && 6489 "Unsupported floating-point vector type"); 6490 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits()); 6491 for (unsigned i = 0; i < NumElts; ++i) 6492 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i))); 6493 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts); 6494 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 6495 Val = LowerBUILD_VECTOR(Val, DAG); 6496 if (Val.getNode()) 6497 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 6498 } 6499 } 6500 6501 // If there was only one constant value used and for more than one lane, 6502 // start by splatting that value, then replace the non-constant lanes. This 6503 // is better than the default, which will perform a separate initialization 6504 // for each lane. 6505 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) { 6506 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue); 6507 // Now insert the non-constant lanes. 6508 for (unsigned i = 0; i < NumElts; ++i) { 6509 SDValue V = Op.getOperand(i); 6510 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 6511 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) { 6512 // Note that type legalization likely mucked about with the VT of the 6513 // source operand, so we may have to convert it here before inserting. 6514 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx); 6515 } 6516 } 6517 return Val; 6518 } 6519 6520 // If all elements are constants and the case above didn't get hit, fall back 6521 // to the default expansion, which will generate a load from the constant 6522 // pool. 6523 if (isConstant) 6524 return SDValue(); 6525 6526 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 6527 if (NumElts >= 4) { 6528 if (SDValue shuffle = ReconstructShuffle(Op, DAG)) 6529 return shuffle; 6530 } 6531 6532 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 6533 // know the default expansion would otherwise fall back on something even 6534 // worse. For a vector with one or two non-undef values, that's 6535 // scalar_to_vector for the elements followed by a shuffle (provided the 6536 // shuffle is valid for the target) and materialization element by element 6537 // on the stack followed by a load for everything else. 6538 if (!isConstant && !usesOnlyOneValue) { 6539 SDValue Vec = DAG.getUNDEF(VT); 6540 SDValue Op0 = Op.getOperand(0); 6541 unsigned ElemSize = VT.getScalarSizeInBits(); 6542 unsigned i = 0; 6543 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to 6544 // a) Avoid a RMW dependency on the full vector register, and 6545 // b) Allow the register coalescer to fold away the copy if the 6546 // value is already in an S or D register. 6547 // Do not do this for UNDEF/LOAD nodes because we have better patterns 6548 // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR. 6549 if (!Op0.isUndef() && Op0.getOpcode() != ISD::LOAD && 6550 (ElemSize == 32 || ElemSize == 64)) { 6551 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub; 6552 MachineSDNode *N = 6553 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0, 6554 DAG.getTargetConstant(SubIdx, dl, MVT::i32)); 6555 Vec = SDValue(N, 0); 6556 ++i; 6557 } 6558 for (; i < NumElts; ++i) { 6559 SDValue V = Op.getOperand(i); 6560 if (V.isUndef()) 6561 continue; 6562 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 6563 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 6564 } 6565 return Vec; 6566 } 6567 6568 // Just use the default expansion. We failed to find a better alternative. 6569 return SDValue(); 6570 } 6571 6572 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 6573 SelectionDAG &DAG) const { 6574 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!"); 6575 6576 // Check for non-constant or out of range lane. 6577 EVT VT = Op.getOperand(0).getValueType(); 6578 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 6579 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 6580 return SDValue(); 6581 6582 6583 // Insertion/extraction are legal for V128 types. 6584 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 6585 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 6586 VT == MVT::v8f16) 6587 return Op; 6588 6589 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 6590 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16) 6591 return SDValue(); 6592 6593 // For V64 types, we perform insertion by expanding the value 6594 // to a V128 type and perform the insertion on that. 6595 SDLoc DL(Op); 6596 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 6597 EVT WideTy = WideVec.getValueType(); 6598 6599 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec, 6600 Op.getOperand(1), Op.getOperand(2)); 6601 // Re-narrow the resultant vector. 6602 return NarrowVector(Node, DAG); 6603 } 6604 6605 SDValue 6606 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 6607 SelectionDAG &DAG) const { 6608 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!"); 6609 6610 // Check for non-constant or out of range lane. 6611 EVT VT = Op.getOperand(0).getValueType(); 6612 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 6613 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 6614 return SDValue(); 6615 6616 6617 // Insertion/extraction are legal for V128 types. 6618 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 6619 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 6620 VT == MVT::v8f16) 6621 return Op; 6622 6623 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 6624 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16) 6625 return SDValue(); 6626 6627 // For V64 types, we perform extraction by expanding the value 6628 // to a V128 type and perform the extraction on that. 6629 SDLoc DL(Op); 6630 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 6631 EVT WideTy = WideVec.getValueType(); 6632 6633 EVT ExtrTy = WideTy.getVectorElementType(); 6634 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8) 6635 ExtrTy = MVT::i32; 6636 6637 // For extractions, we just return the result directly. 6638 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec, 6639 Op.getOperand(1)); 6640 } 6641 6642 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, 6643 SelectionDAG &DAG) const { 6644 EVT VT = Op.getOperand(0).getValueType(); 6645 SDLoc dl(Op); 6646 // Just in case... 6647 if (!VT.isVector()) 6648 return SDValue(); 6649 6650 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 6651 if (!Cst) 6652 return SDValue(); 6653 unsigned Val = Cst->getZExtValue(); 6654 6655 unsigned Size = Op.getValueSizeInBits(); 6656 6657 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel. 6658 if (Val == 0) 6659 return Op; 6660 6661 // If this is extracting the upper 64-bits of a 128-bit vector, we match 6662 // that directly. 6663 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64) 6664 return Op; 6665 6666 return SDValue(); 6667 } 6668 6669 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M, 6670 EVT VT) const { 6671 if (VT.getVectorNumElements() == 4 && 6672 (VT.is128BitVector() || VT.is64BitVector())) { 6673 unsigned PFIndexes[4]; 6674 for (unsigned i = 0; i != 4; ++i) { 6675 if (M[i] < 0) 6676 PFIndexes[i] = 8; 6677 else 6678 PFIndexes[i] = M[i]; 6679 } 6680 6681 // Compute the index in the perfect shuffle table. 6682 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 6683 PFIndexes[2] * 9 + PFIndexes[3]; 6684 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6685 unsigned Cost = (PFEntry >> 30); 6686 6687 if (Cost <= 4) 6688 return true; 6689 } 6690 6691 bool DummyBool; 6692 int DummyInt; 6693 unsigned DummyUnsigned; 6694 6695 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) || 6696 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) || 6697 isEXTMask(M, VT, DummyBool, DummyUnsigned) || 6698 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM. 6699 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) || 6700 isZIPMask(M, VT, DummyUnsigned) || 6701 isTRN_v_undef_Mask(M, VT, DummyUnsigned) || 6702 isUZP_v_undef_Mask(M, VT, DummyUnsigned) || 6703 isZIP_v_undef_Mask(M, VT, DummyUnsigned) || 6704 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) || 6705 isConcatMask(M, VT, VT.getSizeInBits() == 128)); 6706 } 6707 6708 /// getVShiftImm - Check if this is a valid build_vector for the immediate 6709 /// operand of a vector shift operation, where all the elements of the 6710 /// build_vector must have the same constant integer value. 6711 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 6712 // Ignore bit_converts. 6713 while (Op.getOpcode() == ISD::BITCAST) 6714 Op = Op.getOperand(0); 6715 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 6716 APInt SplatBits, SplatUndef; 6717 unsigned SplatBitSize; 6718 bool HasAnyUndefs; 6719 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 6720 HasAnyUndefs, ElementBits) || 6721 SplatBitSize > ElementBits) 6722 return false; 6723 Cnt = SplatBits.getSExtValue(); 6724 return true; 6725 } 6726 6727 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 6728 /// operand of a vector shift left operation. That value must be in the range: 6729 /// 0 <= Value < ElementBits for a left shift; or 6730 /// 0 <= Value <= ElementBits for a long left shift. 6731 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 6732 assert(VT.isVector() && "vector shift count is not a vector type"); 6733 int64_t ElementBits = VT.getScalarSizeInBits(); 6734 if (!getVShiftImm(Op, ElementBits, Cnt)) 6735 return false; 6736 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 6737 } 6738 6739 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 6740 /// operand of a vector shift right operation. The value must be in the range: 6741 /// 1 <= Value <= ElementBits for a right shift; or 6742 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) { 6743 assert(VT.isVector() && "vector shift count is not a vector type"); 6744 int64_t ElementBits = VT.getScalarSizeInBits(); 6745 if (!getVShiftImm(Op, ElementBits, Cnt)) 6746 return false; 6747 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 6748 } 6749 6750 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op, 6751 SelectionDAG &DAG) const { 6752 EVT VT = Op.getValueType(); 6753 SDLoc DL(Op); 6754 int64_t Cnt; 6755 6756 if (!Op.getOperand(1).getValueType().isVector()) 6757 return Op; 6758 unsigned EltSize = VT.getScalarSizeInBits(); 6759 6760 switch (Op.getOpcode()) { 6761 default: 6762 llvm_unreachable("unexpected shift opcode"); 6763 6764 case ISD::SHL: 6765 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) 6766 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0), 6767 DAG.getConstant(Cnt, DL, MVT::i32)); 6768 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 6769 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL, 6770 MVT::i32), 6771 Op.getOperand(0), Op.getOperand(1)); 6772 case ISD::SRA: 6773 case ISD::SRL: 6774 // Right shift immediate 6775 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) { 6776 unsigned Opc = 6777 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR; 6778 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), 6779 DAG.getConstant(Cnt, DL, MVT::i32)); 6780 } 6781 6782 // Right shift register. Note, there is not a shift right register 6783 // instruction, but the shift left register instruction takes a signed 6784 // value, where negative numbers specify a right shift. 6785 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl 6786 : Intrinsic::aarch64_neon_ushl; 6787 // negate the shift amount 6788 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1)); 6789 SDValue NegShiftLeft = 6790 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 6791 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0), 6792 NegShift); 6793 return NegShiftLeft; 6794 } 6795 6796 return SDValue(); 6797 } 6798 6799 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS, 6800 AArch64CC::CondCode CC, bool NoNans, EVT VT, 6801 const SDLoc &dl, SelectionDAG &DAG) { 6802 EVT SrcVT = LHS.getValueType(); 6803 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() && 6804 "function only supposed to emit natural comparisons"); 6805 6806 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 6807 APInt CnstBits(VT.getSizeInBits(), 0); 6808 APInt UndefBits(VT.getSizeInBits(), 0); 6809 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits); 6810 bool IsZero = IsCnst && (CnstBits == 0); 6811 6812 if (SrcVT.getVectorElementType().isFloatingPoint()) { 6813 switch (CC) { 6814 default: 6815 return SDValue(); 6816 case AArch64CC::NE: { 6817 SDValue Fcmeq; 6818 if (IsZero) 6819 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 6820 else 6821 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 6822 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq); 6823 } 6824 case AArch64CC::EQ: 6825 if (IsZero) 6826 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 6827 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 6828 case AArch64CC::GE: 6829 if (IsZero) 6830 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS); 6831 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS); 6832 case AArch64CC::GT: 6833 if (IsZero) 6834 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS); 6835 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS); 6836 case AArch64CC::LS: 6837 if (IsZero) 6838 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS); 6839 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS); 6840 case AArch64CC::LT: 6841 if (!NoNans) 6842 return SDValue(); 6843 // If we ignore NaNs then we can use to the MI implementation. 6844 LLVM_FALLTHROUGH; 6845 case AArch64CC::MI: 6846 if (IsZero) 6847 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS); 6848 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS); 6849 } 6850 } 6851 6852 switch (CC) { 6853 default: 6854 return SDValue(); 6855 case AArch64CC::NE: { 6856 SDValue Cmeq; 6857 if (IsZero) 6858 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 6859 else 6860 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 6861 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq); 6862 } 6863 case AArch64CC::EQ: 6864 if (IsZero) 6865 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 6866 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 6867 case AArch64CC::GE: 6868 if (IsZero) 6869 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS); 6870 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS); 6871 case AArch64CC::GT: 6872 if (IsZero) 6873 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS); 6874 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS); 6875 case AArch64CC::LE: 6876 if (IsZero) 6877 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS); 6878 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS); 6879 case AArch64CC::LS: 6880 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS); 6881 case AArch64CC::LO: 6882 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS); 6883 case AArch64CC::LT: 6884 if (IsZero) 6885 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS); 6886 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS); 6887 case AArch64CC::HI: 6888 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS); 6889 case AArch64CC::HS: 6890 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS); 6891 } 6892 } 6893 6894 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op, 6895 SelectionDAG &DAG) const { 6896 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 6897 SDValue LHS = Op.getOperand(0); 6898 SDValue RHS = Op.getOperand(1); 6899 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger(); 6900 SDLoc dl(Op); 6901 6902 if (LHS.getValueType().getVectorElementType().isInteger()) { 6903 assert(LHS.getValueType() == RHS.getValueType()); 6904 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 6905 SDValue Cmp = 6906 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG); 6907 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 6908 } 6909 6910 if (LHS.getValueType().getVectorElementType() == MVT::f16) 6911 return SDValue(); 6912 6913 assert(LHS.getValueType().getVectorElementType() == MVT::f32 || 6914 LHS.getValueType().getVectorElementType() == MVT::f64); 6915 6916 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 6917 // clean. Some of them require two branches to implement. 6918 AArch64CC::CondCode CC1, CC2; 6919 bool ShouldInvert; 6920 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert); 6921 6922 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath; 6923 SDValue Cmp = 6924 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG); 6925 if (!Cmp.getNode()) 6926 return SDValue(); 6927 6928 if (CC2 != AArch64CC::AL) { 6929 SDValue Cmp2 = 6930 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG); 6931 if (!Cmp2.getNode()) 6932 return SDValue(); 6933 6934 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2); 6935 } 6936 6937 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 6938 6939 if (ShouldInvert) 6940 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType()); 6941 6942 return Cmp; 6943 } 6944 6945 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 6946 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 6947 /// specified in the intrinsic calls. 6948 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 6949 const CallInst &I, 6950 unsigned Intrinsic) const { 6951 auto &DL = I.getModule()->getDataLayout(); 6952 switch (Intrinsic) { 6953 case Intrinsic::aarch64_neon_ld2: 6954 case Intrinsic::aarch64_neon_ld3: 6955 case Intrinsic::aarch64_neon_ld4: 6956 case Intrinsic::aarch64_neon_ld1x2: 6957 case Intrinsic::aarch64_neon_ld1x3: 6958 case Intrinsic::aarch64_neon_ld1x4: 6959 case Intrinsic::aarch64_neon_ld2lane: 6960 case Intrinsic::aarch64_neon_ld3lane: 6961 case Intrinsic::aarch64_neon_ld4lane: 6962 case Intrinsic::aarch64_neon_ld2r: 6963 case Intrinsic::aarch64_neon_ld3r: 6964 case Intrinsic::aarch64_neon_ld4r: { 6965 Info.opc = ISD::INTRINSIC_W_CHAIN; 6966 // Conservatively set memVT to the entire set of vectors loaded. 6967 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 6968 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 6969 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 6970 Info.offset = 0; 6971 Info.align = 0; 6972 Info.vol = false; // volatile loads with NEON intrinsics not supported 6973 Info.readMem = true; 6974 Info.writeMem = false; 6975 return true; 6976 } 6977 case Intrinsic::aarch64_neon_st2: 6978 case Intrinsic::aarch64_neon_st3: 6979 case Intrinsic::aarch64_neon_st4: 6980 case Intrinsic::aarch64_neon_st1x2: 6981 case Intrinsic::aarch64_neon_st1x3: 6982 case Intrinsic::aarch64_neon_st1x4: 6983 case Intrinsic::aarch64_neon_st2lane: 6984 case Intrinsic::aarch64_neon_st3lane: 6985 case Intrinsic::aarch64_neon_st4lane: { 6986 Info.opc = ISD::INTRINSIC_VOID; 6987 // Conservatively set memVT to the entire set of vectors stored. 6988 unsigned NumElts = 0; 6989 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 6990 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 6991 if (!ArgTy->isVectorTy()) 6992 break; 6993 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 6994 } 6995 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 6996 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 6997 Info.offset = 0; 6998 Info.align = 0; 6999 Info.vol = false; // volatile stores with NEON intrinsics not supported 7000 Info.readMem = false; 7001 Info.writeMem = true; 7002 return true; 7003 } 7004 case Intrinsic::aarch64_ldaxr: 7005 case Intrinsic::aarch64_ldxr: { 7006 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 7007 Info.opc = ISD::INTRINSIC_W_CHAIN; 7008 Info.memVT = MVT::getVT(PtrTy->getElementType()); 7009 Info.ptrVal = I.getArgOperand(0); 7010 Info.offset = 0; 7011 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 7012 Info.vol = true; 7013 Info.readMem = true; 7014 Info.writeMem = false; 7015 return true; 7016 } 7017 case Intrinsic::aarch64_stlxr: 7018 case Intrinsic::aarch64_stxr: { 7019 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 7020 Info.opc = ISD::INTRINSIC_W_CHAIN; 7021 Info.memVT = MVT::getVT(PtrTy->getElementType()); 7022 Info.ptrVal = I.getArgOperand(1); 7023 Info.offset = 0; 7024 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 7025 Info.vol = true; 7026 Info.readMem = false; 7027 Info.writeMem = true; 7028 return true; 7029 } 7030 case Intrinsic::aarch64_ldaxp: 7031 case Intrinsic::aarch64_ldxp: { 7032 Info.opc = ISD::INTRINSIC_W_CHAIN; 7033 Info.memVT = MVT::i128; 7034 Info.ptrVal = I.getArgOperand(0); 7035 Info.offset = 0; 7036 Info.align = 16; 7037 Info.vol = true; 7038 Info.readMem = true; 7039 Info.writeMem = false; 7040 return true; 7041 } 7042 case Intrinsic::aarch64_stlxp: 7043 case Intrinsic::aarch64_stxp: { 7044 Info.opc = ISD::INTRINSIC_W_CHAIN; 7045 Info.memVT = MVT::i128; 7046 Info.ptrVal = I.getArgOperand(2); 7047 Info.offset = 0; 7048 Info.align = 16; 7049 Info.vol = true; 7050 Info.readMem = false; 7051 Info.writeMem = true; 7052 return true; 7053 } 7054 default: 7055 break; 7056 } 7057 7058 return false; 7059 } 7060 7061 // Truncations from 64-bit GPR to 32-bit GPR is free. 7062 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 7063 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 7064 return false; 7065 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 7066 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 7067 return NumBits1 > NumBits2; 7068 } 7069 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 7070 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 7071 return false; 7072 unsigned NumBits1 = VT1.getSizeInBits(); 7073 unsigned NumBits2 = VT2.getSizeInBits(); 7074 return NumBits1 > NumBits2; 7075 } 7076 7077 /// Check if it is profitable to hoist instruction in then/else to if. 7078 /// Not profitable if I and it's user can form a FMA instruction 7079 /// because we prefer FMSUB/FMADD. 7080 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const { 7081 if (I->getOpcode() != Instruction::FMul) 7082 return true; 7083 7084 if (I->getNumUses() != 1) 7085 return true; 7086 7087 Instruction *User = I->user_back(); 7088 7089 if (User && 7090 !(User->getOpcode() == Instruction::FSub || 7091 User->getOpcode() == Instruction::FAdd)) 7092 return true; 7093 7094 const TargetOptions &Options = getTargetMachine().Options; 7095 const DataLayout &DL = I->getModule()->getDataLayout(); 7096 EVT VT = getValueType(DL, User->getOperand(0)->getType()); 7097 7098 return !(isFMAFasterThanFMulAndFAdd(VT) && 7099 isOperationLegalOrCustom(ISD::FMA, VT) && 7100 (Options.AllowFPOpFusion == FPOpFusion::Fast || 7101 Options.UnsafeFPMath)); 7102 } 7103 7104 // All 32-bit GPR operations implicitly zero the high-half of the corresponding 7105 // 64-bit GPR. 7106 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const { 7107 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 7108 return false; 7109 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 7110 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 7111 return NumBits1 == 32 && NumBits2 == 64; 7112 } 7113 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 7114 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 7115 return false; 7116 unsigned NumBits1 = VT1.getSizeInBits(); 7117 unsigned NumBits2 = VT2.getSizeInBits(); 7118 return NumBits1 == 32 && NumBits2 == 64; 7119 } 7120 7121 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 7122 EVT VT1 = Val.getValueType(); 7123 if (isZExtFree(VT1, VT2)) { 7124 return true; 7125 } 7126 7127 if (Val.getOpcode() != ISD::LOAD) 7128 return false; 7129 7130 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend. 7131 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() && 7132 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() && 7133 VT1.getSizeInBits() <= 32); 7134 } 7135 7136 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const { 7137 if (isa<FPExtInst>(Ext)) 7138 return false; 7139 7140 // Vector types are next free. 7141 if (Ext->getType()->isVectorTy()) 7142 return false; 7143 7144 for (const Use &U : Ext->uses()) { 7145 // The extension is free if we can fold it with a left shift in an 7146 // addressing mode or an arithmetic operation: add, sub, and cmp. 7147 7148 // Is there a shift? 7149 const Instruction *Instr = cast<Instruction>(U.getUser()); 7150 7151 // Is this a constant shift? 7152 switch (Instr->getOpcode()) { 7153 case Instruction::Shl: 7154 if (!isa<ConstantInt>(Instr->getOperand(1))) 7155 return false; 7156 break; 7157 case Instruction::GetElementPtr: { 7158 gep_type_iterator GTI = gep_type_begin(Instr); 7159 auto &DL = Ext->getModule()->getDataLayout(); 7160 std::advance(GTI, U.getOperandNo()-1); 7161 Type *IdxTy = GTI.getIndexedType(); 7162 // This extension will end up with a shift because of the scaling factor. 7163 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0. 7164 // Get the shift amount based on the scaling factor: 7165 // log2(sizeof(IdxTy)) - log2(8). 7166 uint64_t ShiftAmt = 7167 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3; 7168 // Is the constant foldable in the shift of the addressing mode? 7169 // I.e., shift amount is between 1 and 4 inclusive. 7170 if (ShiftAmt == 0 || ShiftAmt > 4) 7171 return false; 7172 break; 7173 } 7174 case Instruction::Trunc: 7175 // Check if this is a noop. 7176 // trunc(sext ty1 to ty2) to ty1. 7177 if (Instr->getType() == Ext->getOperand(0)->getType()) 7178 continue; 7179 LLVM_FALLTHROUGH; 7180 default: 7181 return false; 7182 } 7183 7184 // At this point we can use the bfm family, so this extension is free 7185 // for that use. 7186 } 7187 return true; 7188 } 7189 7190 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType, 7191 unsigned &RequiredAligment) const { 7192 if (!LoadedType.isSimple() || 7193 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint())) 7194 return false; 7195 // Cyclone supports unaligned accesses. 7196 RequiredAligment = 0; 7197 unsigned NumBits = LoadedType.getSizeInBits(); 7198 return NumBits == 32 || NumBits == 64; 7199 } 7200 7201 /// \brief Lower an interleaved load into a ldN intrinsic. 7202 /// 7203 /// E.g. Lower an interleaved load (Factor = 2): 7204 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr 7205 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 7206 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 7207 /// 7208 /// Into: 7209 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr) 7210 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0 7211 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1 7212 bool AArch64TargetLowering::lowerInterleavedLoad( 7213 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 7214 ArrayRef<unsigned> Indices, unsigned Factor) const { 7215 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 7216 "Invalid interleave factor"); 7217 assert(!Shuffles.empty() && "Empty shufflevector input"); 7218 assert(Shuffles.size() == Indices.size() && 7219 "Unmatched number of shufflevectors and indices"); 7220 7221 const DataLayout &DL = LI->getModule()->getDataLayout(); 7222 7223 VectorType *VecTy = Shuffles[0]->getType(); 7224 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 7225 7226 // Skip if we do not have NEON and skip illegal vector types. 7227 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128)) 7228 return false; 7229 7230 // A pointer vector can not be the return type of the ldN intrinsics. Need to 7231 // load integer vectors first and then convert to pointer vectors. 7232 Type *EltTy = VecTy->getVectorElementType(); 7233 if (EltTy->isPointerTy()) 7234 VecTy = 7235 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 7236 7237 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace()); 7238 Type *Tys[2] = {VecTy, PtrTy}; 7239 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2, 7240 Intrinsic::aarch64_neon_ld3, 7241 Intrinsic::aarch64_neon_ld4}; 7242 Function *LdNFunc = 7243 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 7244 7245 IRBuilder<> Builder(LI); 7246 Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy); 7247 7248 CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN"); 7249 7250 // Replace uses of each shufflevector with the corresponding vector loaded 7251 // by ldN. 7252 for (unsigned i = 0; i < Shuffles.size(); i++) { 7253 ShuffleVectorInst *SVI = Shuffles[i]; 7254 unsigned Index = Indices[i]; 7255 7256 Value *SubVec = Builder.CreateExtractValue(LdN, Index); 7257 7258 // Convert the integer vector to pointer vector if the element is pointer. 7259 if (EltTy->isPointerTy()) 7260 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType()); 7261 7262 SVI->replaceAllUsesWith(SubVec); 7263 } 7264 7265 return true; 7266 } 7267 7268 /// \brief Get a mask consisting of sequential integers starting from \p Start. 7269 /// 7270 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1> 7271 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start, 7272 unsigned NumElts) { 7273 SmallVector<Constant *, 16> Mask; 7274 for (unsigned i = 0; i < NumElts; i++) 7275 Mask.push_back(Builder.getInt32(Start + i)); 7276 7277 return ConstantVector::get(Mask); 7278 } 7279 7280 /// \brief Lower an interleaved store into a stN intrinsic. 7281 /// 7282 /// E.g. Lower an interleaved store (Factor = 3): 7283 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 7284 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 7285 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 7286 /// 7287 /// Into: 7288 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 7289 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 7290 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 7291 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 7292 /// 7293 /// Note that the new shufflevectors will be removed and we'll only generate one 7294 /// st3 instruction in CodeGen. 7295 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI, 7296 ShuffleVectorInst *SVI, 7297 unsigned Factor) const { 7298 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 7299 "Invalid interleave factor"); 7300 7301 VectorType *VecTy = SVI->getType(); 7302 assert(VecTy->getVectorNumElements() % Factor == 0 && 7303 "Invalid interleaved store"); 7304 7305 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor; 7306 Type *EltTy = VecTy->getVectorElementType(); 7307 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts); 7308 7309 const DataLayout &DL = SI->getModule()->getDataLayout(); 7310 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy); 7311 7312 // Skip if we do not have NEON and skip illegal vector types. 7313 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128)) 7314 return false; 7315 7316 Value *Op0 = SVI->getOperand(0); 7317 Value *Op1 = SVI->getOperand(1); 7318 IRBuilder<> Builder(SI); 7319 7320 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 7321 // vectors to integer vectors. 7322 if (EltTy->isPointerTy()) { 7323 Type *IntTy = DL.getIntPtrType(EltTy); 7324 unsigned NumOpElts = 7325 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements(); 7326 7327 // Convert to the corresponding integer vector. 7328 Type *IntVecTy = VectorType::get(IntTy, NumOpElts); 7329 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 7330 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 7331 7332 SubVecTy = VectorType::get(IntTy, NumSubElts); 7333 } 7334 7335 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace()); 7336 Type *Tys[2] = {SubVecTy, PtrTy}; 7337 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2, 7338 Intrinsic::aarch64_neon_st3, 7339 Intrinsic::aarch64_neon_st4}; 7340 Function *StNFunc = 7341 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 7342 7343 SmallVector<Value *, 5> Ops; 7344 7345 // Split the shufflevector operands into sub vectors for the new stN call. 7346 for (unsigned i = 0; i < Factor; i++) 7347 Ops.push_back(Builder.CreateShuffleVector( 7348 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts))); 7349 7350 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy)); 7351 Builder.CreateCall(StNFunc, Ops); 7352 return true; 7353 } 7354 7355 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 7356 unsigned AlignCheck) { 7357 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 7358 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 7359 } 7360 7361 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign, 7362 unsigned SrcAlign, bool IsMemset, 7363 bool ZeroMemset, 7364 bool MemcpyStrSrc, 7365 MachineFunction &MF) const { 7366 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one 7367 // instruction to materialize the v2i64 zero and one store (with restrictive 7368 // addressing mode). Just do two i64 store of zero-registers. 7369 bool Fast; 7370 const Function *F = MF.getFunction(); 7371 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 && 7372 !F->hasFnAttribute(Attribute::NoImplicitFloat) && 7373 (memOpAlign(SrcAlign, DstAlign, 16) || 7374 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast))) 7375 return MVT::f128; 7376 7377 if (Size >= 8 && 7378 (memOpAlign(SrcAlign, DstAlign, 8) || 7379 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast))) 7380 return MVT::i64; 7381 7382 if (Size >= 4 && 7383 (memOpAlign(SrcAlign, DstAlign, 4) || 7384 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast))) 7385 return MVT::i32; 7386 7387 return MVT::Other; 7388 } 7389 7390 // 12-bit optionally shifted immediates are legal for adds. 7391 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const { 7392 // Avoid UB for INT64_MIN. 7393 if (Immed == std::numeric_limits<int64_t>::min()) 7394 return false; 7395 // Same encoding for add/sub, just flip the sign. 7396 Immed = std::abs(Immed); 7397 return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0)); 7398 } 7399 7400 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid 7401 // immediates is the same as for an add or a sub. 7402 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const { 7403 return isLegalAddImmediate(Immed); 7404 } 7405 7406 /// isLegalAddressingMode - Return true if the addressing mode represented 7407 /// by AM is legal for this target, for a load/store of the specified type. 7408 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL, 7409 const AddrMode &AM, Type *Ty, 7410 unsigned AS) const { 7411 // AArch64 has five basic addressing modes: 7412 // reg 7413 // reg + 9-bit signed offset 7414 // reg + SIZE_IN_BYTES * 12-bit unsigned offset 7415 // reg1 + reg2 7416 // reg + SIZE_IN_BYTES * reg 7417 7418 // No global is ever allowed as a base. 7419 if (AM.BaseGV) 7420 return false; 7421 7422 // No reg+reg+imm addressing. 7423 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale) 7424 return false; 7425 7426 // check reg + imm case: 7427 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12 7428 uint64_t NumBytes = 0; 7429 if (Ty->isSized()) { 7430 uint64_t NumBits = DL.getTypeSizeInBits(Ty); 7431 NumBytes = NumBits / 8; 7432 if (!isPowerOf2_64(NumBits)) 7433 NumBytes = 0; 7434 } 7435 7436 if (!AM.Scale) { 7437 int64_t Offset = AM.BaseOffs; 7438 7439 // 9-bit signed offset 7440 if (isInt<9>(Offset)) 7441 return true; 7442 7443 // 12-bit unsigned offset 7444 unsigned shift = Log2_64(NumBytes); 7445 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 && 7446 // Must be a multiple of NumBytes (NumBytes is a power of 2) 7447 (Offset >> shift) << shift == Offset) 7448 return true; 7449 return false; 7450 } 7451 7452 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2 7453 7454 return !AM.Scale || AM.Scale == 1 || 7455 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes); 7456 } 7457 7458 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL, 7459 const AddrMode &AM, Type *Ty, 7460 unsigned AS) const { 7461 // Scaling factors are not free at all. 7462 // Operands | Rt Latency 7463 // ------------------------------------------- 7464 // Rt, [Xn, Xm] | 4 7465 // ------------------------------------------- 7466 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5 7467 // Rt, [Xn, Wm, <extend> #imm] | 7468 if (isLegalAddressingMode(DL, AM, Ty, AS)) 7469 // Scale represents reg2 * scale, thus account for 1 if 7470 // it is not equal to 0 or 1. 7471 return AM.Scale != 0 && AM.Scale != 1; 7472 return -1; 7473 } 7474 7475 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 7476 VT = VT.getScalarType(); 7477 7478 if (!VT.isSimple()) 7479 return false; 7480 7481 switch (VT.getSimpleVT().SimpleTy) { 7482 case MVT::f32: 7483 case MVT::f64: 7484 return true; 7485 default: 7486 break; 7487 } 7488 7489 return false; 7490 } 7491 7492 const MCPhysReg * 7493 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const { 7494 // LR is a callee-save register, but we must treat it as clobbered by any call 7495 // site. Hence we include LR in the scratch registers, which are in turn added 7496 // as implicit-defs for stackmaps and patchpoints. 7497 static const MCPhysReg ScratchRegs[] = { 7498 AArch64::X16, AArch64::X17, AArch64::LR, 0 7499 }; 7500 return ScratchRegs; 7501 } 7502 7503 bool 7504 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const { 7505 EVT VT = N->getValueType(0); 7506 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine 7507 // it with shift to let it be lowered to UBFX. 7508 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) && 7509 isa<ConstantSDNode>(N->getOperand(1))) { 7510 uint64_t TruncMask = N->getConstantOperandVal(1); 7511 if (isMask_64(TruncMask) && 7512 N->getOperand(0).getOpcode() == ISD::SRL && 7513 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1))) 7514 return false; 7515 } 7516 return true; 7517 } 7518 7519 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 7520 Type *Ty) const { 7521 assert(Ty->isIntegerTy()); 7522 7523 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 7524 if (BitSize == 0) 7525 return false; 7526 7527 int64_t Val = Imm.getSExtValue(); 7528 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize)) 7529 return true; 7530 7531 if ((int64_t)Val < 0) 7532 Val = ~Val; 7533 if (BitSize == 32) 7534 Val &= (1LL << 32) - 1; 7535 7536 unsigned LZ = countLeadingZeros((uint64_t)Val); 7537 unsigned Shift = (63 - LZ) / 16; 7538 // MOVZ is free so return true for one or fewer MOVK. 7539 return Shift < 3; 7540 } 7541 7542 /// Turn vector tests of the signbit in the form of: 7543 /// xor (sra X, elt_size(X)-1), -1 7544 /// into: 7545 /// cmge X, X, #0 7546 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG, 7547 const AArch64Subtarget *Subtarget) { 7548 EVT VT = N->getValueType(0); 7549 if (!Subtarget->hasNEON() || !VT.isVector()) 7550 return SDValue(); 7551 7552 // There must be a shift right algebraic before the xor, and the xor must be a 7553 // 'not' operation. 7554 SDValue Shift = N->getOperand(0); 7555 SDValue Ones = N->getOperand(1); 7556 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() || 7557 !ISD::isBuildVectorAllOnes(Ones.getNode())) 7558 return SDValue(); 7559 7560 // The shift should be smearing the sign bit across each vector element. 7561 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 7562 EVT ShiftEltTy = Shift.getValueType().getVectorElementType(); 7563 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1) 7564 return SDValue(); 7565 7566 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0)); 7567 } 7568 7569 // Generate SUBS and CSEL for integer abs. 7570 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) { 7571 EVT VT = N->getValueType(0); 7572 7573 SDValue N0 = N->getOperand(0); 7574 SDValue N1 = N->getOperand(1); 7575 SDLoc DL(N); 7576 7577 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1) 7578 // and change it to SUB and CSEL. 7579 if (VT.isInteger() && N->getOpcode() == ISD::XOR && 7580 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 && 7581 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0)) 7582 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1))) 7583 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) { 7584 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), 7585 N0.getOperand(0)); 7586 // Generate SUBS & CSEL. 7587 SDValue Cmp = 7588 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32), 7589 N0.getOperand(0), DAG.getConstant(0, DL, VT)); 7590 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg, 7591 DAG.getConstant(AArch64CC::PL, DL, MVT::i32), 7592 SDValue(Cmp.getNode(), 1)); 7593 } 7594 return SDValue(); 7595 } 7596 7597 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG, 7598 TargetLowering::DAGCombinerInfo &DCI, 7599 const AArch64Subtarget *Subtarget) { 7600 if (DCI.isBeforeLegalizeOps()) 7601 return SDValue(); 7602 7603 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget)) 7604 return Cmp; 7605 7606 return performIntegerAbsCombine(N, DAG); 7607 } 7608 7609 SDValue 7610 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 7611 SelectionDAG &DAG, 7612 std::vector<SDNode *> *Created) const { 7613 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes(); 7614 if (isIntDivCheap(N->getValueType(0), Attr)) 7615 return SDValue(N,0); // Lower SDIV as SDIV 7616 7617 // fold (sdiv X, pow2) 7618 EVT VT = N->getValueType(0); 7619 if ((VT != MVT::i32 && VT != MVT::i64) || 7620 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 7621 return SDValue(); 7622 7623 SDLoc DL(N); 7624 SDValue N0 = N->getOperand(0); 7625 unsigned Lg2 = Divisor.countTrailingZeros(); 7626 SDValue Zero = DAG.getConstant(0, DL, VT); 7627 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 7628 7629 // Add (N0 < 0) ? Pow2 - 1 : 0; 7630 SDValue CCVal; 7631 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL); 7632 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 7633 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp); 7634 7635 if (Created) { 7636 Created->push_back(Cmp.getNode()); 7637 Created->push_back(Add.getNode()); 7638 Created->push_back(CSel.getNode()); 7639 } 7640 7641 // Divide by pow2. 7642 SDValue SRA = 7643 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64)); 7644 7645 // If we're dividing by a positive value, we're done. Otherwise, we must 7646 // negate the result. 7647 if (Divisor.isNonNegative()) 7648 return SRA; 7649 7650 if (Created) 7651 Created->push_back(SRA.getNode()); 7652 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 7653 } 7654 7655 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG, 7656 TargetLowering::DAGCombinerInfo &DCI, 7657 const AArch64Subtarget *Subtarget) { 7658 if (DCI.isBeforeLegalizeOps()) 7659 return SDValue(); 7660 7661 // The below optimizations require a constant RHS. 7662 if (!isa<ConstantSDNode>(N->getOperand(1))) 7663 return SDValue(); 7664 7665 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1)); 7666 const APInt &ConstValue = C->getAPIntValue(); 7667 7668 // Multiplication of a power of two plus/minus one can be done more 7669 // cheaply as as shift+add/sub. For now, this is true unilaterally. If 7670 // future CPUs have a cheaper MADD instruction, this may need to be 7671 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and 7672 // 64-bit is 5 cycles, so this is always a win. 7673 // More aggressively, some multiplications N0 * C can be lowered to 7674 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M, 7675 // e.g. 6=3*2=(2+1)*2. 7676 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45 7677 // which equals to (1+2)*16-(1+2). 7678 SDValue N0 = N->getOperand(0); 7679 // TrailingZeroes is used to test if the mul can be lowered to 7680 // shift+add+shift. 7681 unsigned TrailingZeroes = ConstValue.countTrailingZeros(); 7682 if (TrailingZeroes) { 7683 // Conservatively do not lower to shift+add+shift if the mul might be 7684 // folded into smul or umul. 7685 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) || 7686 isZeroExtended(N0.getNode(), DAG))) 7687 return SDValue(); 7688 // Conservatively do not lower to shift+add+shift if the mul might be 7689 // folded into madd or msub. 7690 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD || 7691 N->use_begin()->getOpcode() == ISD::SUB)) 7692 return SDValue(); 7693 } 7694 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub 7695 // and shift+add+shift. 7696 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes); 7697 7698 unsigned ShiftAmt, AddSubOpc; 7699 // Is the shifted value the LHS operand of the add/sub? 7700 bool ShiftValUseIsN0 = true; 7701 // Do we need to negate the result? 7702 bool NegateResult = false; 7703 7704 if (ConstValue.isNonNegative()) { 7705 // (mul x, 2^N + 1) => (add (shl x, N), x) 7706 // (mul x, 2^N - 1) => (sub (shl x, N), x) 7707 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M) 7708 APInt SCVMinus1 = ShiftedConstValue - 1; 7709 APInt CVPlus1 = ConstValue + 1; 7710 if (SCVMinus1.isPowerOf2()) { 7711 ShiftAmt = SCVMinus1.logBase2(); 7712 AddSubOpc = ISD::ADD; 7713 } else if (CVPlus1.isPowerOf2()) { 7714 ShiftAmt = CVPlus1.logBase2(); 7715 AddSubOpc = ISD::SUB; 7716 } else 7717 return SDValue(); 7718 } else { 7719 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 7720 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 7721 APInt CVNegPlus1 = -ConstValue + 1; 7722 APInt CVNegMinus1 = -ConstValue - 1; 7723 if (CVNegPlus1.isPowerOf2()) { 7724 ShiftAmt = CVNegPlus1.logBase2(); 7725 AddSubOpc = ISD::SUB; 7726 ShiftValUseIsN0 = false; 7727 } else if (CVNegMinus1.isPowerOf2()) { 7728 ShiftAmt = CVNegMinus1.logBase2(); 7729 AddSubOpc = ISD::ADD; 7730 NegateResult = true; 7731 } else 7732 return SDValue(); 7733 } 7734 7735 SDLoc DL(N); 7736 EVT VT = N->getValueType(0); 7737 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0, 7738 DAG.getConstant(ShiftAmt, DL, MVT::i64)); 7739 7740 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0; 7741 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal; 7742 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1); 7743 assert(!(NegateResult && TrailingZeroes) && 7744 "NegateResult and TrailingZeroes cannot both be true for now."); 7745 // Negate the result. 7746 if (NegateResult) 7747 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 7748 // Shift the result. 7749 if (TrailingZeroes) 7750 return DAG.getNode(ISD::SHL, DL, VT, Res, 7751 DAG.getConstant(TrailingZeroes, DL, MVT::i64)); 7752 return Res; 7753 } 7754 7755 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N, 7756 SelectionDAG &DAG) { 7757 // Take advantage of vector comparisons producing 0 or -1 in each lane to 7758 // optimize away operation when it's from a constant. 7759 // 7760 // The general transformation is: 7761 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) --> 7762 // AND(VECTOR_CMP(x,y), constant2) 7763 // constant2 = UNARYOP(constant) 7764 7765 // Early exit if this isn't a vector operation, the operand of the 7766 // unary operation isn't a bitwise AND, or if the sizes of the operations 7767 // aren't the same. 7768 EVT VT = N->getValueType(0); 7769 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND || 7770 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC || 7771 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits()) 7772 return SDValue(); 7773 7774 // Now check that the other operand of the AND is a constant. We could 7775 // make the transformation for non-constant splats as well, but it's unclear 7776 // that would be a benefit as it would not eliminate any operations, just 7777 // perform one more step in scalar code before moving to the vector unit. 7778 if (BuildVectorSDNode *BV = 7779 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) { 7780 // Bail out if the vector isn't a constant. 7781 if (!BV->isConstant()) 7782 return SDValue(); 7783 7784 // Everything checks out. Build up the new and improved node. 7785 SDLoc DL(N); 7786 EVT IntVT = BV->getValueType(0); 7787 // Create a new constant of the appropriate type for the transformed 7788 // DAG. 7789 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0)); 7790 // The AND node needs bitcasts to/from an integer vector type around it. 7791 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst); 7792 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT, 7793 N->getOperand(0)->getOperand(0), MaskConst); 7794 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd); 7795 return Res; 7796 } 7797 7798 return SDValue(); 7799 } 7800 7801 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG, 7802 const AArch64Subtarget *Subtarget) { 7803 // First try to optimize away the conversion when it's conditionally from 7804 // a constant. Vectors only. 7805 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG)) 7806 return Res; 7807 7808 EVT VT = N->getValueType(0); 7809 if (VT != MVT::f32 && VT != MVT::f64) 7810 return SDValue(); 7811 7812 // Only optimize when the source and destination types have the same width. 7813 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits()) 7814 return SDValue(); 7815 7816 // If the result of an integer load is only used by an integer-to-float 7817 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead. 7818 // This eliminates an "integer-to-vector-move" UOP and improves throughput. 7819 SDValue N0 = N->getOperand(0); 7820 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 7821 // Do not change the width of a volatile load. 7822 !cast<LoadSDNode>(N0)->isVolatile()) { 7823 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 7824 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 7825 LN0->getPointerInfo(), LN0->getAlignment(), 7826 LN0->getMemOperand()->getFlags()); 7827 7828 // Make sure successors of the original load stay after it by updating them 7829 // to use the new Chain. 7830 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1)); 7831 7832 unsigned Opcode = 7833 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF; 7834 return DAG.getNode(Opcode, SDLoc(N), VT, Load); 7835 } 7836 7837 return SDValue(); 7838 } 7839 7840 /// Fold a floating-point multiply by power of two into floating-point to 7841 /// fixed-point conversion. 7842 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG, 7843 TargetLowering::DAGCombinerInfo &DCI, 7844 const AArch64Subtarget *Subtarget) { 7845 if (!Subtarget->hasNEON()) 7846 return SDValue(); 7847 7848 SDValue Op = N->getOperand(0); 7849 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 7850 Op.getOpcode() != ISD::FMUL) 7851 return SDValue(); 7852 7853 SDValue ConstVec = Op->getOperand(1); 7854 if (!isa<BuildVectorSDNode>(ConstVec)) 7855 return SDValue(); 7856 7857 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 7858 uint32_t FloatBits = FloatTy.getSizeInBits(); 7859 if (FloatBits != 32 && FloatBits != 64) 7860 return SDValue(); 7861 7862 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 7863 uint32_t IntBits = IntTy.getSizeInBits(); 7864 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 7865 return SDValue(); 7866 7867 // Avoid conversions where iN is larger than the float (e.g., float -> i64). 7868 if (IntBits > FloatBits) 7869 return SDValue(); 7870 7871 BitVector UndefElements; 7872 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 7873 int32_t Bits = IntBits == 64 ? 64 : 32; 7874 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1); 7875 if (C == -1 || C == 0 || C > Bits) 7876 return SDValue(); 7877 7878 MVT ResTy; 7879 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 7880 switch (NumLanes) { 7881 default: 7882 return SDValue(); 7883 case 2: 7884 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 7885 break; 7886 case 4: 7887 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; 7888 break; 7889 } 7890 7891 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) 7892 return SDValue(); 7893 7894 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) && 7895 "Illegal vector type after legalization"); 7896 7897 SDLoc DL(N); 7898 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 7899 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs 7900 : Intrinsic::aarch64_neon_vcvtfp2fxu; 7901 SDValue FixConv = 7902 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy, 7903 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), 7904 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32)); 7905 // We can handle smaller integers by generating an extra trunc. 7906 if (IntBits < FloatBits) 7907 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv); 7908 7909 return FixConv; 7910 } 7911 7912 /// Fold a floating-point divide by power of two into fixed-point to 7913 /// floating-point conversion. 7914 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG, 7915 TargetLowering::DAGCombinerInfo &DCI, 7916 const AArch64Subtarget *Subtarget) { 7917 if (!Subtarget->hasNEON()) 7918 return SDValue(); 7919 7920 SDValue Op = N->getOperand(0); 7921 unsigned Opc = Op->getOpcode(); 7922 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 7923 !Op.getOperand(0).getValueType().isSimple() || 7924 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP)) 7925 return SDValue(); 7926 7927 SDValue ConstVec = N->getOperand(1); 7928 if (!isa<BuildVectorSDNode>(ConstVec)) 7929 return SDValue(); 7930 7931 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 7932 int32_t IntBits = IntTy.getSizeInBits(); 7933 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 7934 return SDValue(); 7935 7936 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 7937 int32_t FloatBits = FloatTy.getSizeInBits(); 7938 if (FloatBits != 32 && FloatBits != 64) 7939 return SDValue(); 7940 7941 // Avoid conversions where iN is larger than the float (e.g., i64 -> float). 7942 if (IntBits > FloatBits) 7943 return SDValue(); 7944 7945 BitVector UndefElements; 7946 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 7947 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1); 7948 if (C == -1 || C == 0 || C > FloatBits) 7949 return SDValue(); 7950 7951 MVT ResTy; 7952 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 7953 switch (NumLanes) { 7954 default: 7955 return SDValue(); 7956 case 2: 7957 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 7958 break; 7959 case 4: 7960 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; 7961 break; 7962 } 7963 7964 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) 7965 return SDValue(); 7966 7967 SDLoc DL(N); 7968 SDValue ConvInput = Op.getOperand(0); 7969 bool IsSigned = Opc == ISD::SINT_TO_FP; 7970 if (IntBits < FloatBits) 7971 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, 7972 ResTy, ConvInput); 7973 7974 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp 7975 : Intrinsic::aarch64_neon_vcvtfxu2fp; 7976 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(), 7977 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput, 7978 DAG.getConstant(C, DL, MVT::i32)); 7979 } 7980 7981 /// An EXTR instruction is made up of two shifts, ORed together. This helper 7982 /// searches for and classifies those shifts. 7983 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount, 7984 bool &FromHi) { 7985 if (N.getOpcode() == ISD::SHL) 7986 FromHi = false; 7987 else if (N.getOpcode() == ISD::SRL) 7988 FromHi = true; 7989 else 7990 return false; 7991 7992 if (!isa<ConstantSDNode>(N.getOperand(1))) 7993 return false; 7994 7995 ShiftAmount = N->getConstantOperandVal(1); 7996 Src = N->getOperand(0); 7997 return true; 7998 } 7999 8000 /// EXTR instruction extracts a contiguous chunk of bits from two existing 8001 /// registers viewed as a high/low pair. This function looks for the pattern: 8002 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an 8003 /// EXTR. Can't quite be done in TableGen because the two immediates aren't 8004 /// independent. 8005 static SDValue tryCombineToEXTR(SDNode *N, 8006 TargetLowering::DAGCombinerInfo &DCI) { 8007 SelectionDAG &DAG = DCI.DAG; 8008 SDLoc DL(N); 8009 EVT VT = N->getValueType(0); 8010 8011 assert(N->getOpcode() == ISD::OR && "Unexpected root"); 8012 8013 if (VT != MVT::i32 && VT != MVT::i64) 8014 return SDValue(); 8015 8016 SDValue LHS; 8017 uint32_t ShiftLHS = 0; 8018 bool LHSFromHi = 0; 8019 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi)) 8020 return SDValue(); 8021 8022 SDValue RHS; 8023 uint32_t ShiftRHS = 0; 8024 bool RHSFromHi = 0; 8025 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi)) 8026 return SDValue(); 8027 8028 // If they're both trying to come from the high part of the register, they're 8029 // not really an EXTR. 8030 if (LHSFromHi == RHSFromHi) 8031 return SDValue(); 8032 8033 if (ShiftLHS + ShiftRHS != VT.getSizeInBits()) 8034 return SDValue(); 8035 8036 if (LHSFromHi) { 8037 std::swap(LHS, RHS); 8038 std::swap(ShiftLHS, ShiftRHS); 8039 } 8040 8041 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS, 8042 DAG.getConstant(ShiftRHS, DL, MVT::i64)); 8043 } 8044 8045 static SDValue tryCombineToBSL(SDNode *N, 8046 TargetLowering::DAGCombinerInfo &DCI) { 8047 EVT VT = N->getValueType(0); 8048 SelectionDAG &DAG = DCI.DAG; 8049 SDLoc DL(N); 8050 8051 if (!VT.isVector()) 8052 return SDValue(); 8053 8054 SDValue N0 = N->getOperand(0); 8055 if (N0.getOpcode() != ISD::AND) 8056 return SDValue(); 8057 8058 SDValue N1 = N->getOperand(1); 8059 if (N1.getOpcode() != ISD::AND) 8060 return SDValue(); 8061 8062 // We only have to look for constant vectors here since the general, variable 8063 // case can be handled in TableGen. 8064 unsigned Bits = VT.getScalarSizeInBits(); 8065 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1); 8066 for (int i = 1; i >= 0; --i) 8067 for (int j = 1; j >= 0; --j) { 8068 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i)); 8069 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j)); 8070 if (!BVN0 || !BVN1) 8071 continue; 8072 8073 bool FoundMatch = true; 8074 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) { 8075 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k)); 8076 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k)); 8077 if (!CN0 || !CN1 || 8078 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) { 8079 FoundMatch = false; 8080 break; 8081 } 8082 } 8083 8084 if (FoundMatch) 8085 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0), 8086 N0->getOperand(1 - i), N1->getOperand(1 - j)); 8087 } 8088 8089 return SDValue(); 8090 } 8091 8092 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 8093 const AArch64Subtarget *Subtarget) { 8094 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) 8095 SelectionDAG &DAG = DCI.DAG; 8096 EVT VT = N->getValueType(0); 8097 8098 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 8099 return SDValue(); 8100 8101 if (SDValue Res = tryCombineToEXTR(N, DCI)) 8102 return Res; 8103 8104 if (SDValue Res = tryCombineToBSL(N, DCI)) 8105 return Res; 8106 8107 return SDValue(); 8108 } 8109 8110 static SDValue performSRLCombine(SDNode *N, 8111 TargetLowering::DAGCombinerInfo &DCI) { 8112 SelectionDAG &DAG = DCI.DAG; 8113 EVT VT = N->getValueType(0); 8114 if (VT != MVT::i32 && VT != MVT::i64) 8115 return SDValue(); 8116 8117 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the 8118 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32) 8119 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero. 8120 SDValue N0 = N->getOperand(0); 8121 if (N0.getOpcode() == ISD::BSWAP) { 8122 SDLoc DL(N); 8123 SDValue N1 = N->getOperand(1); 8124 SDValue N00 = N0.getOperand(0); 8125 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 8126 uint64_t ShiftAmt = C->getZExtValue(); 8127 if (VT == MVT::i32 && ShiftAmt == 16 && 8128 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16))) 8129 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 8130 if (VT == MVT::i64 && ShiftAmt == 32 && 8131 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32))) 8132 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 8133 } 8134 } 8135 return SDValue(); 8136 } 8137 8138 static SDValue performBitcastCombine(SDNode *N, 8139 TargetLowering::DAGCombinerInfo &DCI, 8140 SelectionDAG &DAG) { 8141 // Wait 'til after everything is legalized to try this. That way we have 8142 // legal vector types and such. 8143 if (DCI.isBeforeLegalizeOps()) 8144 return SDValue(); 8145 8146 // Remove extraneous bitcasts around an extract_subvector. 8147 // For example, 8148 // (v4i16 (bitconvert 8149 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1))))) 8150 // becomes 8151 // (extract_subvector ((v8i16 ...), (i64 4))) 8152 8153 // Only interested in 64-bit vectors as the ultimate result. 8154 EVT VT = N->getValueType(0); 8155 if (!VT.isVector()) 8156 return SDValue(); 8157 if (VT.getSimpleVT().getSizeInBits() != 64) 8158 return SDValue(); 8159 // Is the operand an extract_subvector starting at the beginning or halfway 8160 // point of the vector? A low half may also come through as an 8161 // EXTRACT_SUBREG, so look for that, too. 8162 SDValue Op0 = N->getOperand(0); 8163 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR && 8164 !(Op0->isMachineOpcode() && 8165 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG)) 8166 return SDValue(); 8167 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue(); 8168 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) { 8169 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0) 8170 return SDValue(); 8171 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) { 8172 if (idx != AArch64::dsub) 8173 return SDValue(); 8174 // The dsub reference is equivalent to a lane zero subvector reference. 8175 idx = 0; 8176 } 8177 // Look through the bitcast of the input to the extract. 8178 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST) 8179 return SDValue(); 8180 SDValue Source = Op0->getOperand(0)->getOperand(0); 8181 // If the source type has twice the number of elements as our destination 8182 // type, we know this is an extract of the high or low half of the vector. 8183 EVT SVT = Source->getValueType(0); 8184 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2) 8185 return SDValue(); 8186 8187 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n"); 8188 8189 // Create the simplified form to just extract the low or high half of the 8190 // vector directly rather than bothering with the bitcasts. 8191 SDLoc dl(N); 8192 unsigned NumElements = VT.getVectorNumElements(); 8193 if (idx) { 8194 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64); 8195 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx); 8196 } else { 8197 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32); 8198 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT, 8199 Source, SubReg), 8200 0); 8201 } 8202 } 8203 8204 static SDValue performConcatVectorsCombine(SDNode *N, 8205 TargetLowering::DAGCombinerInfo &DCI, 8206 SelectionDAG &DAG) { 8207 SDLoc dl(N); 8208 EVT VT = N->getValueType(0); 8209 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 8210 8211 // Optimize concat_vectors of truncated vectors, where the intermediate 8212 // type is illegal, to avoid said illegality, e.g., 8213 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))), 8214 // (v2i16 (truncate (v2i64))))) 8215 // -> 8216 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))), 8217 // (v4i32 (bitcast (v2i64))), 8218 // <0, 2, 4, 6>))) 8219 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed 8220 // on both input and result type, so we might generate worse code. 8221 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8. 8222 if (N->getNumOperands() == 2 && 8223 N0->getOpcode() == ISD::TRUNCATE && 8224 N1->getOpcode() == ISD::TRUNCATE) { 8225 SDValue N00 = N0->getOperand(0); 8226 SDValue N10 = N1->getOperand(0); 8227 EVT N00VT = N00.getValueType(); 8228 8229 if (N00VT == N10.getValueType() && 8230 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) && 8231 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) { 8232 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16); 8233 SmallVector<int, 8> Mask(MidVT.getVectorNumElements()); 8234 for (size_t i = 0; i < Mask.size(); ++i) 8235 Mask[i] = i * 2; 8236 return DAG.getNode(ISD::TRUNCATE, dl, VT, 8237 DAG.getVectorShuffle( 8238 MidVT, dl, 8239 DAG.getNode(ISD::BITCAST, dl, MidVT, N00), 8240 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask)); 8241 } 8242 } 8243 8244 // Wait 'til after everything is legalized to try this. That way we have 8245 // legal vector types and such. 8246 if (DCI.isBeforeLegalizeOps()) 8247 return SDValue(); 8248 8249 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector 8250 // splat. The indexed instructions are going to be expecting a DUPLANE64, so 8251 // canonicalise to that. 8252 if (N0 == N1 && VT.getVectorNumElements() == 2) { 8253 assert(VT.getScalarSizeInBits() == 64); 8254 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG), 8255 DAG.getConstant(0, dl, MVT::i64)); 8256 } 8257 8258 // Canonicalise concat_vectors so that the right-hand vector has as few 8259 // bit-casts as possible before its real operation. The primary matching 8260 // destination for these operations will be the narrowing "2" instructions, 8261 // which depend on the operation being performed on this right-hand vector. 8262 // For example, 8263 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS)))) 8264 // becomes 8265 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS)) 8266 8267 if (N1->getOpcode() != ISD::BITCAST) 8268 return SDValue(); 8269 SDValue RHS = N1->getOperand(0); 8270 MVT RHSTy = RHS.getValueType().getSimpleVT(); 8271 // If the RHS is not a vector, this is not the pattern we're looking for. 8272 if (!RHSTy.isVector()) 8273 return SDValue(); 8274 8275 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n"); 8276 8277 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(), 8278 RHSTy.getVectorNumElements() * 2); 8279 return DAG.getNode(ISD::BITCAST, dl, VT, 8280 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy, 8281 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0), 8282 RHS)); 8283 } 8284 8285 static SDValue tryCombineFixedPointConvert(SDNode *N, 8286 TargetLowering::DAGCombinerInfo &DCI, 8287 SelectionDAG &DAG) { 8288 // Wait 'til after everything is legalized to try this. That way we have 8289 // legal vector types and such. 8290 if (DCI.isBeforeLegalizeOps()) 8291 return SDValue(); 8292 // Transform a scalar conversion of a value from a lane extract into a 8293 // lane extract of a vector conversion. E.g., from foo1 to foo2: 8294 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); } 8295 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; } 8296 // 8297 // The second form interacts better with instruction selection and the 8298 // register allocator to avoid cross-class register copies that aren't 8299 // coalescable due to a lane reference. 8300 8301 // Check the operand and see if it originates from a lane extract. 8302 SDValue Op1 = N->getOperand(1); 8303 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 8304 // Yep, no additional predication needed. Perform the transform. 8305 SDValue IID = N->getOperand(0); 8306 SDValue Shift = N->getOperand(2); 8307 SDValue Vec = Op1.getOperand(0); 8308 SDValue Lane = Op1.getOperand(1); 8309 EVT ResTy = N->getValueType(0); 8310 EVT VecResTy; 8311 SDLoc DL(N); 8312 8313 // The vector width should be 128 bits by the time we get here, even 8314 // if it started as 64 bits (the extract_vector handling will have 8315 // done so). 8316 assert(Vec.getValueSizeInBits() == 128 && 8317 "unexpected vector size on extract_vector_elt!"); 8318 if (Vec.getValueType() == MVT::v4i32) 8319 VecResTy = MVT::v4f32; 8320 else if (Vec.getValueType() == MVT::v2i64) 8321 VecResTy = MVT::v2f64; 8322 else 8323 llvm_unreachable("unexpected vector type!"); 8324 8325 SDValue Convert = 8326 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift); 8327 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane); 8328 } 8329 return SDValue(); 8330 } 8331 8332 // AArch64 high-vector "long" operations are formed by performing the non-high 8333 // version on an extract_subvector of each operand which gets the high half: 8334 // 8335 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS)) 8336 // 8337 // However, there are cases which don't have an extract_high explicitly, but 8338 // have another operation that can be made compatible with one for free. For 8339 // example: 8340 // 8341 // (dupv64 scalar) --> (extract_high (dup128 scalar)) 8342 // 8343 // This routine does the actual conversion of such DUPs, once outer routines 8344 // have determined that everything else is in order. 8345 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold 8346 // similarly here. 8347 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) { 8348 switch (N.getOpcode()) { 8349 case AArch64ISD::DUP: 8350 case AArch64ISD::DUPLANE8: 8351 case AArch64ISD::DUPLANE16: 8352 case AArch64ISD::DUPLANE32: 8353 case AArch64ISD::DUPLANE64: 8354 case AArch64ISD::MOVI: 8355 case AArch64ISD::MOVIshift: 8356 case AArch64ISD::MOVIedit: 8357 case AArch64ISD::MOVImsl: 8358 case AArch64ISD::MVNIshift: 8359 case AArch64ISD::MVNImsl: 8360 break; 8361 default: 8362 // FMOV could be supported, but isn't very useful, as it would only occur 8363 // if you passed a bitcast' floating point immediate to an eligible long 8364 // integer op (addl, smull, ...). 8365 return SDValue(); 8366 } 8367 8368 MVT NarrowTy = N.getSimpleValueType(); 8369 if (!NarrowTy.is64BitVector()) 8370 return SDValue(); 8371 8372 MVT ElementTy = NarrowTy.getVectorElementType(); 8373 unsigned NumElems = NarrowTy.getVectorNumElements(); 8374 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2); 8375 8376 SDLoc dl(N); 8377 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy, 8378 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()), 8379 DAG.getConstant(NumElems, dl, MVT::i64)); 8380 } 8381 8382 static bool isEssentiallyExtractSubvector(SDValue N) { 8383 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR) 8384 return true; 8385 8386 return N.getOpcode() == ISD::BITCAST && 8387 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR; 8388 } 8389 8390 /// \brief Helper structure to keep track of ISD::SET_CC operands. 8391 struct GenericSetCCInfo { 8392 const SDValue *Opnd0; 8393 const SDValue *Opnd1; 8394 ISD::CondCode CC; 8395 }; 8396 8397 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code. 8398 struct AArch64SetCCInfo { 8399 const SDValue *Cmp; 8400 AArch64CC::CondCode CC; 8401 }; 8402 8403 /// \brief Helper structure to keep track of SetCC information. 8404 union SetCCInfo { 8405 GenericSetCCInfo Generic; 8406 AArch64SetCCInfo AArch64; 8407 }; 8408 8409 /// \brief Helper structure to be able to read SetCC information. If set to 8410 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a 8411 /// GenericSetCCInfo. 8412 struct SetCCInfoAndKind { 8413 SetCCInfo Info; 8414 bool IsAArch64; 8415 }; 8416 8417 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or 8418 /// an 8419 /// AArch64 lowered one. 8420 /// \p SetCCInfo is filled accordingly. 8421 /// \post SetCCInfo is meanginfull only when this function returns true. 8422 /// \return True when Op is a kind of SET_CC operation. 8423 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) { 8424 // If this is a setcc, this is straight forward. 8425 if (Op.getOpcode() == ISD::SETCC) { 8426 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0); 8427 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1); 8428 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 8429 SetCCInfo.IsAArch64 = false; 8430 return true; 8431 } 8432 // Otherwise, check if this is a matching csel instruction. 8433 // In other words: 8434 // - csel 1, 0, cc 8435 // - csel 0, 1, !cc 8436 if (Op.getOpcode() != AArch64ISD::CSEL) 8437 return false; 8438 // Set the information about the operands. 8439 // TODO: we want the operands of the Cmp not the csel 8440 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3); 8441 SetCCInfo.IsAArch64 = true; 8442 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>( 8443 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); 8444 8445 // Check that the operands matches the constraints: 8446 // (1) Both operands must be constants. 8447 // (2) One must be 1 and the other must be 0. 8448 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0)); 8449 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8450 8451 // Check (1). 8452 if (!TValue || !FValue) 8453 return false; 8454 8455 // Check (2). 8456 if (!TValue->isOne()) { 8457 // Update the comparison when we are interested in !cc. 8458 std::swap(TValue, FValue); 8459 SetCCInfo.Info.AArch64.CC = 8460 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC); 8461 } 8462 return TValue->isOne() && FValue->isNullValue(); 8463 } 8464 8465 // Returns true if Op is setcc or zext of setcc. 8466 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) { 8467 if (isSetCC(Op, Info)) 8468 return true; 8469 return ((Op.getOpcode() == ISD::ZERO_EXTEND) && 8470 isSetCC(Op->getOperand(0), Info)); 8471 } 8472 8473 // The folding we want to perform is: 8474 // (add x, [zext] (setcc cc ...) ) 8475 // --> 8476 // (csel x, (add x, 1), !cc ...) 8477 // 8478 // The latter will get matched to a CSINC instruction. 8479 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) { 8480 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!"); 8481 SDValue LHS = Op->getOperand(0); 8482 SDValue RHS = Op->getOperand(1); 8483 SetCCInfoAndKind InfoAndKind; 8484 8485 // If neither operand is a SET_CC, give up. 8486 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) { 8487 std::swap(LHS, RHS); 8488 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) 8489 return SDValue(); 8490 } 8491 8492 // FIXME: This could be generatized to work for FP comparisons. 8493 EVT CmpVT = InfoAndKind.IsAArch64 8494 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType() 8495 : InfoAndKind.Info.Generic.Opnd0->getValueType(); 8496 if (CmpVT != MVT::i32 && CmpVT != MVT::i64) 8497 return SDValue(); 8498 8499 SDValue CCVal; 8500 SDValue Cmp; 8501 SDLoc dl(Op); 8502 if (InfoAndKind.IsAArch64) { 8503 CCVal = DAG.getConstant( 8504 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl, 8505 MVT::i32); 8506 Cmp = *InfoAndKind.Info.AArch64.Cmp; 8507 } else 8508 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0, 8509 *InfoAndKind.Info.Generic.Opnd1, 8510 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true), 8511 CCVal, DAG, dl); 8512 8513 EVT VT = Op->getValueType(0); 8514 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT)); 8515 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp); 8516 } 8517 8518 // The basic add/sub long vector instructions have variants with "2" on the end 8519 // which act on the high-half of their inputs. They are normally matched by 8520 // patterns like: 8521 // 8522 // (add (zeroext (extract_high LHS)), 8523 // (zeroext (extract_high RHS))) 8524 // -> uaddl2 vD, vN, vM 8525 // 8526 // However, if one of the extracts is something like a duplicate, this 8527 // instruction can still be used profitably. This function puts the DAG into a 8528 // more appropriate form for those patterns to trigger. 8529 static SDValue performAddSubLongCombine(SDNode *N, 8530 TargetLowering::DAGCombinerInfo &DCI, 8531 SelectionDAG &DAG) { 8532 if (DCI.isBeforeLegalizeOps()) 8533 return SDValue(); 8534 8535 MVT VT = N->getSimpleValueType(0); 8536 if (!VT.is128BitVector()) { 8537 if (N->getOpcode() == ISD::ADD) 8538 return performSetccAddFolding(N, DAG); 8539 return SDValue(); 8540 } 8541 8542 // Make sure both branches are extended in the same way. 8543 SDValue LHS = N->getOperand(0); 8544 SDValue RHS = N->getOperand(1); 8545 if ((LHS.getOpcode() != ISD::ZERO_EXTEND && 8546 LHS.getOpcode() != ISD::SIGN_EXTEND) || 8547 LHS.getOpcode() != RHS.getOpcode()) 8548 return SDValue(); 8549 8550 unsigned ExtType = LHS.getOpcode(); 8551 8552 // It's not worth doing if at least one of the inputs isn't already an 8553 // extract, but we don't know which it'll be so we have to try both. 8554 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) { 8555 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG); 8556 if (!RHS.getNode()) 8557 return SDValue(); 8558 8559 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS); 8560 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) { 8561 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG); 8562 if (!LHS.getNode()) 8563 return SDValue(); 8564 8565 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS); 8566 } 8567 8568 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS); 8569 } 8570 8571 // Massage DAGs which we can use the high-half "long" operations on into 8572 // something isel will recognize better. E.g. 8573 // 8574 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) --> 8575 // (aarch64_neon_umull (extract_high (v2i64 vec))) 8576 // (extract_high (v2i64 (dup128 scalar))))) 8577 // 8578 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N, 8579 TargetLowering::DAGCombinerInfo &DCI, 8580 SelectionDAG &DAG) { 8581 if (DCI.isBeforeLegalizeOps()) 8582 return SDValue(); 8583 8584 SDValue LHS = N->getOperand(1); 8585 SDValue RHS = N->getOperand(2); 8586 assert(LHS.getValueType().is64BitVector() && 8587 RHS.getValueType().is64BitVector() && 8588 "unexpected shape for long operation"); 8589 8590 // Either node could be a DUP, but it's not worth doing both of them (you'd 8591 // just as well use the non-high version) so look for a corresponding extract 8592 // operation on the other "wing". 8593 if (isEssentiallyExtractSubvector(LHS)) { 8594 RHS = tryExtendDUPToExtractHigh(RHS, DAG); 8595 if (!RHS.getNode()) 8596 return SDValue(); 8597 } else if (isEssentiallyExtractSubvector(RHS)) { 8598 LHS = tryExtendDUPToExtractHigh(LHS, DAG); 8599 if (!LHS.getNode()) 8600 return SDValue(); 8601 } 8602 8603 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0), 8604 N->getOperand(0), LHS, RHS); 8605 } 8606 8607 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) { 8608 MVT ElemTy = N->getSimpleValueType(0).getScalarType(); 8609 unsigned ElemBits = ElemTy.getSizeInBits(); 8610 8611 int64_t ShiftAmount; 8612 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) { 8613 APInt SplatValue, SplatUndef; 8614 unsigned SplatBitSize; 8615 bool HasAnyUndefs; 8616 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 8617 HasAnyUndefs, ElemBits) || 8618 SplatBitSize != ElemBits) 8619 return SDValue(); 8620 8621 ShiftAmount = SplatValue.getSExtValue(); 8622 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) { 8623 ShiftAmount = CVN->getSExtValue(); 8624 } else 8625 return SDValue(); 8626 8627 unsigned Opcode; 8628 bool IsRightShift; 8629 switch (IID) { 8630 default: 8631 llvm_unreachable("Unknown shift intrinsic"); 8632 case Intrinsic::aarch64_neon_sqshl: 8633 Opcode = AArch64ISD::SQSHL_I; 8634 IsRightShift = false; 8635 break; 8636 case Intrinsic::aarch64_neon_uqshl: 8637 Opcode = AArch64ISD::UQSHL_I; 8638 IsRightShift = false; 8639 break; 8640 case Intrinsic::aarch64_neon_srshl: 8641 Opcode = AArch64ISD::SRSHR_I; 8642 IsRightShift = true; 8643 break; 8644 case Intrinsic::aarch64_neon_urshl: 8645 Opcode = AArch64ISD::URSHR_I; 8646 IsRightShift = true; 8647 break; 8648 case Intrinsic::aarch64_neon_sqshlu: 8649 Opcode = AArch64ISD::SQSHLU_I; 8650 IsRightShift = false; 8651 break; 8652 } 8653 8654 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) { 8655 SDLoc dl(N); 8656 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 8657 DAG.getConstant(-ShiftAmount, dl, MVT::i32)); 8658 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) { 8659 SDLoc dl(N); 8660 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 8661 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 8662 } 8663 8664 return SDValue(); 8665 } 8666 8667 // The CRC32[BH] instructions ignore the high bits of their data operand. Since 8668 // the intrinsics must be legal and take an i32, this means there's almost 8669 // certainly going to be a zext in the DAG which we can eliminate. 8670 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) { 8671 SDValue AndN = N->getOperand(2); 8672 if (AndN.getOpcode() != ISD::AND) 8673 return SDValue(); 8674 8675 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1)); 8676 if (!CMask || CMask->getZExtValue() != Mask) 8677 return SDValue(); 8678 8679 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32, 8680 N->getOperand(0), N->getOperand(1), AndN.getOperand(0)); 8681 } 8682 8683 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N, 8684 SelectionDAG &DAG) { 8685 SDLoc dl(N); 8686 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), 8687 DAG.getNode(Opc, dl, 8688 N->getOperand(1).getSimpleValueType(), 8689 N->getOperand(1)), 8690 DAG.getConstant(0, dl, MVT::i64)); 8691 } 8692 8693 static SDValue performIntrinsicCombine(SDNode *N, 8694 TargetLowering::DAGCombinerInfo &DCI, 8695 const AArch64Subtarget *Subtarget) { 8696 SelectionDAG &DAG = DCI.DAG; 8697 unsigned IID = getIntrinsicID(N); 8698 switch (IID) { 8699 default: 8700 break; 8701 case Intrinsic::aarch64_neon_vcvtfxs2fp: 8702 case Intrinsic::aarch64_neon_vcvtfxu2fp: 8703 return tryCombineFixedPointConvert(N, DCI, DAG); 8704 case Intrinsic::aarch64_neon_saddv: 8705 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG); 8706 case Intrinsic::aarch64_neon_uaddv: 8707 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG); 8708 case Intrinsic::aarch64_neon_sminv: 8709 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG); 8710 case Intrinsic::aarch64_neon_uminv: 8711 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG); 8712 case Intrinsic::aarch64_neon_smaxv: 8713 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG); 8714 case Intrinsic::aarch64_neon_umaxv: 8715 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG); 8716 case Intrinsic::aarch64_neon_fmax: 8717 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0), 8718 N->getOperand(1), N->getOperand(2)); 8719 case Intrinsic::aarch64_neon_fmin: 8720 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0), 8721 N->getOperand(1), N->getOperand(2)); 8722 case Intrinsic::aarch64_neon_fmaxnm: 8723 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0), 8724 N->getOperand(1), N->getOperand(2)); 8725 case Intrinsic::aarch64_neon_fminnm: 8726 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0), 8727 N->getOperand(1), N->getOperand(2)); 8728 case Intrinsic::aarch64_neon_smull: 8729 case Intrinsic::aarch64_neon_umull: 8730 case Intrinsic::aarch64_neon_pmull: 8731 case Intrinsic::aarch64_neon_sqdmull: 8732 return tryCombineLongOpWithDup(IID, N, DCI, DAG); 8733 case Intrinsic::aarch64_neon_sqshl: 8734 case Intrinsic::aarch64_neon_uqshl: 8735 case Intrinsic::aarch64_neon_sqshlu: 8736 case Intrinsic::aarch64_neon_srshl: 8737 case Intrinsic::aarch64_neon_urshl: 8738 return tryCombineShiftImm(IID, N, DAG); 8739 case Intrinsic::aarch64_crc32b: 8740 case Intrinsic::aarch64_crc32cb: 8741 return tryCombineCRC32(0xff, N, DAG); 8742 case Intrinsic::aarch64_crc32h: 8743 case Intrinsic::aarch64_crc32ch: 8744 return tryCombineCRC32(0xffff, N, DAG); 8745 } 8746 return SDValue(); 8747 } 8748 8749 static SDValue performExtendCombine(SDNode *N, 8750 TargetLowering::DAGCombinerInfo &DCI, 8751 SelectionDAG &DAG) { 8752 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then 8753 // we can convert that DUP into another extract_high (of a bigger DUP), which 8754 // helps the backend to decide that an sabdl2 would be useful, saving a real 8755 // extract_high operation. 8756 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND && 8757 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) { 8758 SDNode *ABDNode = N->getOperand(0).getNode(); 8759 unsigned IID = getIntrinsicID(ABDNode); 8760 if (IID == Intrinsic::aarch64_neon_sabd || 8761 IID == Intrinsic::aarch64_neon_uabd) { 8762 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG); 8763 if (!NewABD.getNode()) 8764 return SDValue(); 8765 8766 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), 8767 NewABD); 8768 } 8769 } 8770 8771 // This is effectively a custom type legalization for AArch64. 8772 // 8773 // Type legalization will split an extend of a small, legal, type to a larger 8774 // illegal type by first splitting the destination type, often creating 8775 // illegal source types, which then get legalized in isel-confusing ways, 8776 // leading to really terrible codegen. E.g., 8777 // %result = v8i32 sext v8i8 %value 8778 // becomes 8779 // %losrc = extract_subreg %value, ... 8780 // %hisrc = extract_subreg %value, ... 8781 // %lo = v4i32 sext v4i8 %losrc 8782 // %hi = v4i32 sext v4i8 %hisrc 8783 // Things go rapidly downhill from there. 8784 // 8785 // For AArch64, the [sz]ext vector instructions can only go up one element 8786 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32 8787 // take two instructions. 8788 // 8789 // This implies that the most efficient way to do the extend from v8i8 8790 // to two v4i32 values is to first extend the v8i8 to v8i16, then do 8791 // the normal splitting to happen for the v8i16->v8i32. 8792 8793 // This is pre-legalization to catch some cases where the default 8794 // type legalization will create ill-tempered code. 8795 if (!DCI.isBeforeLegalizeOps()) 8796 return SDValue(); 8797 8798 // We're only interested in cleaning things up for non-legal vector types 8799 // here. If both the source and destination are legal, things will just 8800 // work naturally without any fiddling. 8801 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8802 EVT ResVT = N->getValueType(0); 8803 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT)) 8804 return SDValue(); 8805 // If the vector type isn't a simple VT, it's beyond the scope of what 8806 // we're worried about here. Let legalization do its thing and hope for 8807 // the best. 8808 SDValue Src = N->getOperand(0); 8809 EVT SrcVT = Src->getValueType(0); 8810 if (!ResVT.isSimple() || !SrcVT.isSimple()) 8811 return SDValue(); 8812 8813 // If the source VT is a 64-bit vector, we can play games and get the 8814 // better results we want. 8815 if (SrcVT.getSizeInBits() != 64) 8816 return SDValue(); 8817 8818 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 8819 unsigned ElementCount = SrcVT.getVectorNumElements(); 8820 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount); 8821 SDLoc DL(N); 8822 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src); 8823 8824 // Now split the rest of the operation into two halves, each with a 64 8825 // bit source. 8826 EVT LoVT, HiVT; 8827 SDValue Lo, Hi; 8828 unsigned NumElements = ResVT.getVectorNumElements(); 8829 assert(!(NumElements & 1) && "Splitting vector, but not in half!"); 8830 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(), 8831 ResVT.getVectorElementType(), NumElements / 2); 8832 8833 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(), 8834 LoVT.getVectorNumElements()); 8835 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 8836 DAG.getConstant(0, DL, MVT::i64)); 8837 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 8838 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64)); 8839 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo); 8840 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi); 8841 8842 // Now combine the parts back together so we still have a single result 8843 // like the combiner expects. 8844 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi); 8845 } 8846 8847 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St, 8848 SDValue SplatVal, unsigned NumVecElts) { 8849 unsigned OrigAlignment = St.getAlignment(); 8850 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8; 8851 8852 // Create scalar stores. This is at least as good as the code sequence for a 8853 // split unaligned store which is a dup.s, ext.b, and two stores. 8854 // Most of the time the three stores should be replaced by store pair 8855 // instructions (stp). 8856 SDLoc DL(&St); 8857 SDValue BasePtr = St.getBasePtr(); 8858 SDValue NewST1 = 8859 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, St.getPointerInfo(), 8860 OrigAlignment, St.getMemOperand()->getFlags()); 8861 8862 unsigned Offset = EltOffset; 8863 while (--NumVecElts) { 8864 unsigned Alignment = MinAlign(OrigAlignment, Offset); 8865 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 8866 DAG.getConstant(Offset, DL, MVT::i64)); 8867 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr, 8868 St.getPointerInfo(), Alignment, 8869 St.getMemOperand()->getFlags()); 8870 Offset += EltOffset; 8871 } 8872 return NewST1; 8873 } 8874 8875 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The 8876 /// load store optimizer pass will merge them to store pair stores. This should 8877 /// be better than a movi to create the vector zero followed by a vector store 8878 /// if the zero constant is not re-used, since one instructions and one register 8879 /// live range will be removed. 8880 /// 8881 /// For example, the final generated code should be: 8882 /// 8883 /// stp xzr, xzr, [x0] 8884 /// 8885 /// instead of: 8886 /// 8887 /// movi v0.2d, #0 8888 /// str q0, [x0] 8889 /// 8890 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) { 8891 SDValue StVal = St.getValue(); 8892 EVT VT = StVal.getValueType(); 8893 8894 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or 8895 // 2, 3 or 4 i32 elements. 8896 int NumVecElts = VT.getVectorNumElements(); 8897 if (!(((NumVecElts == 2 || NumVecElts == 3) && 8898 VT.getVectorElementType().getSizeInBits() == 64) || 8899 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) && 8900 VT.getVectorElementType().getSizeInBits() == 32))) 8901 return SDValue(); 8902 8903 if (StVal.getOpcode() != ISD::BUILD_VECTOR) 8904 return SDValue(); 8905 8906 // If the zero constant has more than one use then the vector store could be 8907 // better since the constant mov will be amortized and stp q instructions 8908 // should be able to be formed. 8909 if (!StVal.hasOneUse()) 8910 return SDValue(); 8911 8912 // If the immediate offset of the address operand is too large for the stp 8913 // instruction, then bail out. 8914 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) { 8915 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1); 8916 if (Offset < -512 || Offset > 504) 8917 return SDValue(); 8918 } 8919 8920 for (int I = 0; I < NumVecElts; ++I) { 8921 SDValue EltVal = StVal.getOperand(I); 8922 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal)) 8923 return SDValue(); 8924 } 8925 8926 // Use WZR/XZR here to prevent DAGCombiner::MergeConsecutiveStores from 8927 // undoing this transformation. 8928 SDValue SplatVal = VT.getVectorElementType().getSizeInBits() == 32 8929 ? DAG.getRegister(AArch64::WZR, MVT::i32) 8930 : DAG.getRegister(AArch64::XZR, MVT::i64); 8931 return splitStoreSplat(DAG, St, SplatVal, NumVecElts); 8932 } 8933 8934 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar 8935 /// value. The load store optimizer pass will merge them to store pair stores. 8936 /// This has better performance than a splat of the scalar followed by a split 8937 /// vector store. Even if the stores are not merged it is four stores vs a dup, 8938 /// followed by an ext.b and two stores. 8939 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) { 8940 SDValue StVal = St.getValue(); 8941 EVT VT = StVal.getValueType(); 8942 8943 // Don't replace floating point stores, they possibly won't be transformed to 8944 // stp because of the store pair suppress pass. 8945 if (VT.isFloatingPoint()) 8946 return SDValue(); 8947 8948 // We can express a splat as store pair(s) for 2 or 4 elements. 8949 unsigned NumVecElts = VT.getVectorNumElements(); 8950 if (NumVecElts != 4 && NumVecElts != 2) 8951 return SDValue(); 8952 8953 // Check that this is a splat. 8954 // Make sure that each of the relevant vector element locations are inserted 8955 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32. 8956 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1); 8957 SDValue SplatVal; 8958 for (unsigned I = 0; I < NumVecElts; ++I) { 8959 // Check for insert vector elements. 8960 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT) 8961 return SDValue(); 8962 8963 // Check that same value is inserted at each vector element. 8964 if (I == 0) 8965 SplatVal = StVal.getOperand(1); 8966 else if (StVal.getOperand(1) != SplatVal) 8967 return SDValue(); 8968 8969 // Check insert element index. 8970 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2)); 8971 if (!CIndex) 8972 return SDValue(); 8973 uint64_t IndexVal = CIndex->getZExtValue(); 8974 if (IndexVal >= NumVecElts) 8975 return SDValue(); 8976 IndexNotInserted.reset(IndexVal); 8977 8978 StVal = StVal.getOperand(0); 8979 } 8980 // Check that all vector element locations were inserted to. 8981 if (IndexNotInserted.any()) 8982 return SDValue(); 8983 8984 return splitStoreSplat(DAG, St, SplatVal, NumVecElts); 8985 } 8986 8987 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 8988 SelectionDAG &DAG, 8989 const AArch64Subtarget *Subtarget) { 8990 if (!DCI.isBeforeLegalize()) 8991 return SDValue(); 8992 8993 StoreSDNode *S = cast<StoreSDNode>(N); 8994 if (S->isVolatile()) 8995 return SDValue(); 8996 8997 SDValue StVal = S->getValue(); 8998 EVT VT = StVal.getValueType(); 8999 if (!VT.isVector()) 9000 return SDValue(); 9001 9002 // If we get a splat of zeros, convert this vector store to a store of 9003 // scalars. They will be merged into store pairs of xzr thereby removing one 9004 // instruction and one register. 9005 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S)) 9006 return ReplacedZeroSplat; 9007 9008 // FIXME: The logic for deciding if an unaligned store should be split should 9009 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be 9010 // a call to that function here. 9011 9012 if (!Subtarget->isMisaligned128StoreSlow()) 9013 return SDValue(); 9014 9015 // Don't split at -Oz. 9016 if (DAG.getMachineFunction().getFunction()->optForMinSize()) 9017 return SDValue(); 9018 9019 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting 9020 // those up regresses performance on micro-benchmarks and olden/bh. 9021 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64) 9022 return SDValue(); 9023 9024 // Split unaligned 16B stores. They are terrible for performance. 9025 // Don't split stores with alignment of 1 or 2. Code that uses clang vector 9026 // extensions can use this to mark that it does not want splitting to happen 9027 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of 9028 // eliminating alignment hazards is only 1 in 8 for alignment of 2. 9029 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 || 9030 S->getAlignment() <= 2) 9031 return SDValue(); 9032 9033 // If we get a splat of a scalar convert this vector store to a store of 9034 // scalars. They will be merged into store pairs thereby removing two 9035 // instructions. 9036 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S)) 9037 return ReplacedSplat; 9038 9039 SDLoc DL(S); 9040 unsigned NumElts = VT.getVectorNumElements() / 2; 9041 // Split VT into two. 9042 EVT HalfVT = 9043 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts); 9044 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 9045 DAG.getConstant(0, DL, MVT::i64)); 9046 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 9047 DAG.getConstant(NumElts, DL, MVT::i64)); 9048 SDValue BasePtr = S->getBasePtr(); 9049 SDValue NewST1 = 9050 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(), 9051 S->getAlignment(), S->getMemOperand()->getFlags()); 9052 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 9053 DAG.getConstant(8, DL, MVT::i64)); 9054 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr, 9055 S->getPointerInfo(), S->getAlignment(), 9056 S->getMemOperand()->getFlags()); 9057 } 9058 9059 /// Target-specific DAG combine function for post-increment LD1 (lane) and 9060 /// post-increment LD1R. 9061 static SDValue performPostLD1Combine(SDNode *N, 9062 TargetLowering::DAGCombinerInfo &DCI, 9063 bool IsLaneOp) { 9064 if (DCI.isBeforeLegalizeOps()) 9065 return SDValue(); 9066 9067 SelectionDAG &DAG = DCI.DAG; 9068 EVT VT = N->getValueType(0); 9069 9070 unsigned LoadIdx = IsLaneOp ? 1 : 0; 9071 SDNode *LD = N->getOperand(LoadIdx).getNode(); 9072 // If it is not LOAD, can not do such combine. 9073 if (LD->getOpcode() != ISD::LOAD) 9074 return SDValue(); 9075 9076 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD); 9077 EVT MemVT = LoadSDN->getMemoryVT(); 9078 // Check if memory operand is the same type as the vector element. 9079 if (MemVT != VT.getVectorElementType()) 9080 return SDValue(); 9081 9082 // Check if there are other uses. If so, do not combine as it will introduce 9083 // an extra load. 9084 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE; 9085 ++UI) { 9086 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result. 9087 continue; 9088 if (*UI != N) 9089 return SDValue(); 9090 } 9091 9092 SDValue Addr = LD->getOperand(1); 9093 SDValue Vector = N->getOperand(0); 9094 // Search for a use of the address operand that is an increment. 9095 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE = 9096 Addr.getNode()->use_end(); UI != UE; ++UI) { 9097 SDNode *User = *UI; 9098 if (User->getOpcode() != ISD::ADD 9099 || UI.getUse().getResNo() != Addr.getResNo()) 9100 continue; 9101 9102 // Check that the add is independent of the load. Otherwise, folding it 9103 // would create a cycle. 9104 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User)) 9105 continue; 9106 // Also check that add is not used in the vector operand. This would also 9107 // create a cycle. 9108 if (User->isPredecessorOf(Vector.getNode())) 9109 continue; 9110 9111 // If the increment is a constant, it must match the memory ref size. 9112 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 9113 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 9114 uint32_t IncVal = CInc->getZExtValue(); 9115 unsigned NumBytes = VT.getScalarSizeInBits() / 8; 9116 if (IncVal != NumBytes) 9117 continue; 9118 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 9119 } 9120 9121 // Finally, check that the vector doesn't depend on the load. 9122 // Again, this would create a cycle. 9123 // The load depending on the vector is fine, as that's the case for the 9124 // LD1*post we'll eventually generate anyway. 9125 if (LoadSDN->isPredecessorOf(Vector.getNode())) 9126 continue; 9127 9128 SmallVector<SDValue, 8> Ops; 9129 Ops.push_back(LD->getOperand(0)); // Chain 9130 if (IsLaneOp) { 9131 Ops.push_back(Vector); // The vector to be inserted 9132 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector 9133 } 9134 Ops.push_back(Addr); 9135 Ops.push_back(Inc); 9136 9137 EVT Tys[3] = { VT, MVT::i64, MVT::Other }; 9138 SDVTList SDTys = DAG.getVTList(Tys); 9139 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost; 9140 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops, 9141 MemVT, 9142 LoadSDN->getMemOperand()); 9143 9144 // Update the uses. 9145 SDValue NewResults[] = { 9146 SDValue(LD, 0), // The result of load 9147 SDValue(UpdN.getNode(), 2) // Chain 9148 }; 9149 DCI.CombineTo(LD, NewResults); 9150 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result 9151 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register 9152 9153 break; 9154 } 9155 return SDValue(); 9156 } 9157 9158 /// Simplify \Addr given that the top byte of it is ignored by HW during 9159 /// address translation. 9160 static bool performTBISimplification(SDValue Addr, 9161 TargetLowering::DAGCombinerInfo &DCI, 9162 SelectionDAG &DAG) { 9163 APInt DemandedMask = APInt::getLowBitsSet(64, 56); 9164 APInt KnownZero, KnownOne; 9165 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(), 9166 DCI.isBeforeLegalizeOps()); 9167 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 9168 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) { 9169 DCI.CommitTargetLoweringOpt(TLO); 9170 return true; 9171 } 9172 return false; 9173 } 9174 9175 static SDValue performSTORECombine(SDNode *N, 9176 TargetLowering::DAGCombinerInfo &DCI, 9177 SelectionDAG &DAG, 9178 const AArch64Subtarget *Subtarget) { 9179 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget)) 9180 return Split; 9181 9182 if (Subtarget->supportsAddressTopByteIgnored() && 9183 performTBISimplification(N->getOperand(2), DCI, DAG)) 9184 return SDValue(N, 0); 9185 9186 return SDValue(); 9187 } 9188 9189 /// This function handles the log2-shuffle pattern produced by the 9190 /// LoopVectorizer for the across vector reduction. It consists of 9191 /// log2(NumVectorElements) steps and, in each step, 2^(s) elements 9192 /// are reduced, where s is an induction variable from 0 to 9193 /// log2(NumVectorElements). 9194 static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV, 9195 unsigned Op, 9196 SelectionDAG &DAG) { 9197 EVT VTy = OpV->getOperand(0).getValueType(); 9198 if (!VTy.isVector()) 9199 return SDValue(); 9200 9201 int NumVecElts = VTy.getVectorNumElements(); 9202 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) { 9203 if (NumVecElts != 4) 9204 return SDValue(); 9205 } else { 9206 if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16) 9207 return SDValue(); 9208 } 9209 9210 int NumExpectedSteps = APInt(8, NumVecElts).logBase2(); 9211 SDValue PreOp = OpV; 9212 // Iterate over each step of the across vector reduction. 9213 for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) { 9214 SDValue CurOp = PreOp.getOperand(0); 9215 SDValue Shuffle = PreOp.getOperand(1); 9216 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) { 9217 // Try to swap the 1st and 2nd operand as add and min/max instructions 9218 // are commutative. 9219 CurOp = PreOp.getOperand(1); 9220 Shuffle = PreOp.getOperand(0); 9221 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) 9222 return SDValue(); 9223 } 9224 9225 // Check if the input vector is fed by the operator we want to handle, 9226 // except the last step; the very first input vector is not necessarily 9227 // the same operator we are handling. 9228 if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1))) 9229 return SDValue(); 9230 9231 // Check if it forms one step of the across vector reduction. 9232 // E.g., 9233 // %cur = add %1, %0 9234 // %shuffle = vector_shuffle %cur, <2, 3, u, u> 9235 // %pre = add %cur, %shuffle 9236 if (Shuffle.getOperand(0) != CurOp) 9237 return SDValue(); 9238 9239 int NumMaskElts = 1 << CurStep; 9240 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask(); 9241 // Check mask values in each step. 9242 // We expect the shuffle mask in each step follows a specific pattern 9243 // denoted here by the <M, U> form, where M is a sequence of integers 9244 // starting from NumMaskElts, increasing by 1, and the number integers 9245 // in M should be NumMaskElts. U is a sequence of UNDEFs and the number 9246 // of undef in U should be NumVecElts - NumMaskElts. 9247 // E.g., for <8 x i16>, mask values in each step should be : 9248 // step 0 : <1,u,u,u,u,u,u,u> 9249 // step 1 : <2,3,u,u,u,u,u,u> 9250 // step 2 : <4,5,6,7,u,u,u,u> 9251 for (int i = 0; i < NumVecElts; ++i) 9252 if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) || 9253 (i >= NumMaskElts && !(Mask[i] < 0))) 9254 return SDValue(); 9255 9256 PreOp = CurOp; 9257 } 9258 unsigned Opcode; 9259 bool IsIntrinsic = false; 9260 9261 switch (Op) { 9262 default: 9263 llvm_unreachable("Unexpected operator for across vector reduction"); 9264 case ISD::ADD: 9265 Opcode = AArch64ISD::UADDV; 9266 break; 9267 case ISD::SMAX: 9268 Opcode = AArch64ISD::SMAXV; 9269 break; 9270 case ISD::UMAX: 9271 Opcode = AArch64ISD::UMAXV; 9272 break; 9273 case ISD::SMIN: 9274 Opcode = AArch64ISD::SMINV; 9275 break; 9276 case ISD::UMIN: 9277 Opcode = AArch64ISD::UMINV; 9278 break; 9279 case ISD::FMAXNUM: 9280 Opcode = Intrinsic::aarch64_neon_fmaxnmv; 9281 IsIntrinsic = true; 9282 break; 9283 case ISD::FMINNUM: 9284 Opcode = Intrinsic::aarch64_neon_fminnmv; 9285 IsIntrinsic = true; 9286 break; 9287 } 9288 SDLoc DL(N); 9289 9290 return IsIntrinsic 9291 ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0), 9292 DAG.getConstant(Opcode, DL, MVT::i32), PreOp) 9293 : DAG.getNode( 9294 ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), 9295 DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp), 9296 DAG.getConstant(0, DL, MVT::i64)); 9297 } 9298 9299 /// Target-specific DAG combine for the across vector min/max reductions. 9300 /// This function specifically handles the final clean-up step of the vector 9301 /// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle 9302 /// pattern, which narrows down and finds the final min/max value from all 9303 /// elements of the vector. 9304 /// For example, for a <16 x i8> vector : 9305 /// svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u> 9306 /// %smax0 = smax %arr, svn0 9307 /// %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u> 9308 /// %smax1 = smax %smax0, %svn1 9309 /// %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u> 9310 /// %smax2 = smax %smax1, svn2 9311 /// %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u> 9312 /// %sc = setcc %smax2, %svn3, gt 9313 /// %n0 = extract_vector_elt %sc, #0 9314 /// %n1 = extract_vector_elt %smax2, #0 9315 /// %n2 = extract_vector_elt $smax2, #1 9316 /// %result = select %n0, %n1, n2 9317 /// becomes : 9318 /// %1 = smaxv %0 9319 /// %result = extract_vector_elt %1, 0 9320 static SDValue 9321 performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG, 9322 const AArch64Subtarget *Subtarget) { 9323 if (!Subtarget->hasNEON()) 9324 return SDValue(); 9325 9326 SDValue N0 = N->getOperand(0); 9327 SDValue IfTrue = N->getOperand(1); 9328 SDValue IfFalse = N->getOperand(2); 9329 9330 // Check if the SELECT merges up the final result of the min/max 9331 // from a vector. 9332 if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9333 IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 9334 IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 9335 return SDValue(); 9336 9337 // Expect N0 is fed by SETCC. 9338 SDValue SetCC = N0.getOperand(0); 9339 EVT SetCCVT = SetCC.getValueType(); 9340 if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() || 9341 SetCCVT.getVectorElementType() != MVT::i1) 9342 return SDValue(); 9343 9344 SDValue VectorOp = SetCC.getOperand(0); 9345 unsigned Op = VectorOp->getOpcode(); 9346 // Check if the input vector is fed by the operator we want to handle. 9347 if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN && 9348 Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM) 9349 return SDValue(); 9350 9351 EVT VTy = VectorOp.getValueType(); 9352 if (!VTy.isVector()) 9353 return SDValue(); 9354 9355 if (VTy.getSizeInBits() < 64) 9356 return SDValue(); 9357 9358 EVT EltTy = VTy.getVectorElementType(); 9359 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) { 9360 if (EltTy != MVT::f32) 9361 return SDValue(); 9362 } else { 9363 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8) 9364 return SDValue(); 9365 } 9366 9367 // Check if extracting from the same vector. 9368 // For example, 9369 // %sc = setcc %vector, %svn1, gt 9370 // %n0 = extract_vector_elt %sc, #0 9371 // %n1 = extract_vector_elt %vector, #0 9372 // %n2 = extract_vector_elt $vector, #1 9373 if (!(VectorOp == IfTrue->getOperand(0) && 9374 VectorOp == IfFalse->getOperand(0))) 9375 return SDValue(); 9376 9377 // Check if the condition code is matched with the operator type. 9378 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get(); 9379 if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) || 9380 (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) || 9381 (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) || 9382 (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) || 9383 (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE && 9384 CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT && 9385 CC != ISD::SETGE) || 9386 (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE && 9387 CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT && 9388 CC != ISD::SETLE)) 9389 return SDValue(); 9390 9391 // Expect to check only lane 0 from the vector SETCC. 9392 if (!isNullConstant(N0.getOperand(1))) 9393 return SDValue(); 9394 9395 // Expect to extract the true value from lane 0. 9396 if (!isNullConstant(IfTrue.getOperand(1))) 9397 return SDValue(); 9398 9399 // Expect to extract the false value from lane 1. 9400 if (!isOneConstant(IfFalse.getOperand(1))) 9401 return SDValue(); 9402 9403 return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG); 9404 } 9405 9406 /// Target-specific DAG combine for the across vector add reduction. 9407 /// This function specifically handles the final clean-up step of the vector 9408 /// add reduction produced by the LoopVectorizer. It is the log2-shuffle 9409 /// pattern, which adds all elements of a vector together. 9410 /// For example, for a <4 x i32> vector : 9411 /// %1 = vector_shuffle %0, <2,3,u,u> 9412 /// %2 = add %0, %1 9413 /// %3 = vector_shuffle %2, <1,u,u,u> 9414 /// %4 = add %2, %3 9415 /// %result = extract_vector_elt %4, 0 9416 /// becomes : 9417 /// %0 = uaddv %0 9418 /// %result = extract_vector_elt %0, 0 9419 static SDValue 9420 performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG, 9421 const AArch64Subtarget *Subtarget) { 9422 if (!Subtarget->hasNEON()) 9423 return SDValue(); 9424 SDValue N0 = N->getOperand(0); 9425 SDValue N1 = N->getOperand(1); 9426 9427 // Check if the input vector is fed by the ADD. 9428 if (N0->getOpcode() != ISD::ADD) 9429 return SDValue(); 9430 9431 // The vector extract idx must constant zero because we only expect the final 9432 // result of the reduction is placed in lane 0. 9433 if (!isNullConstant(N1)) 9434 return SDValue(); 9435 9436 EVT VTy = N0.getValueType(); 9437 if (!VTy.isVector()) 9438 return SDValue(); 9439 9440 EVT EltTy = VTy.getVectorElementType(); 9441 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8) 9442 return SDValue(); 9443 9444 if (VTy.getSizeInBits() < 64) 9445 return SDValue(); 9446 9447 return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG); 9448 } 9449 9450 /// Target-specific DAG combine function for NEON load/store intrinsics 9451 /// to merge base address updates. 9452 static SDValue performNEONPostLDSTCombine(SDNode *N, 9453 TargetLowering::DAGCombinerInfo &DCI, 9454 SelectionDAG &DAG) { 9455 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 9456 return SDValue(); 9457 9458 unsigned AddrOpIdx = N->getNumOperands() - 1; 9459 SDValue Addr = N->getOperand(AddrOpIdx); 9460 9461 // Search for a use of the address operand that is an increment. 9462 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 9463 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 9464 SDNode *User = *UI; 9465 if (User->getOpcode() != ISD::ADD || 9466 UI.getUse().getResNo() != Addr.getResNo()) 9467 continue; 9468 9469 // Check that the add is independent of the load/store. Otherwise, folding 9470 // it would create a cycle. 9471 if (User->isPredecessorOf(N) || N->isPredecessorOf(User)) 9472 continue; 9473 9474 // Find the new opcode for the updating load/store. 9475 bool IsStore = false; 9476 bool IsLaneOp = false; 9477 bool IsDupOp = false; 9478 unsigned NewOpc = 0; 9479 unsigned NumVecs = 0; 9480 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 9481 switch (IntNo) { 9482 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 9483 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post; 9484 NumVecs = 2; break; 9485 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post; 9486 NumVecs = 3; break; 9487 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post; 9488 NumVecs = 4; break; 9489 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post; 9490 NumVecs = 2; IsStore = true; break; 9491 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post; 9492 NumVecs = 3; IsStore = true; break; 9493 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post; 9494 NumVecs = 4; IsStore = true; break; 9495 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post; 9496 NumVecs = 2; break; 9497 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post; 9498 NumVecs = 3; break; 9499 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post; 9500 NumVecs = 4; break; 9501 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post; 9502 NumVecs = 2; IsStore = true; break; 9503 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post; 9504 NumVecs = 3; IsStore = true; break; 9505 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post; 9506 NumVecs = 4; IsStore = true; break; 9507 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost; 9508 NumVecs = 2; IsDupOp = true; break; 9509 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost; 9510 NumVecs = 3; IsDupOp = true; break; 9511 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost; 9512 NumVecs = 4; IsDupOp = true; break; 9513 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost; 9514 NumVecs = 2; IsLaneOp = true; break; 9515 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost; 9516 NumVecs = 3; IsLaneOp = true; break; 9517 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost; 9518 NumVecs = 4; IsLaneOp = true; break; 9519 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost; 9520 NumVecs = 2; IsStore = true; IsLaneOp = true; break; 9521 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost; 9522 NumVecs = 3; IsStore = true; IsLaneOp = true; break; 9523 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost; 9524 NumVecs = 4; IsStore = true; IsLaneOp = true; break; 9525 } 9526 9527 EVT VecTy; 9528 if (IsStore) 9529 VecTy = N->getOperand(2).getValueType(); 9530 else 9531 VecTy = N->getValueType(0); 9532 9533 // If the increment is a constant, it must match the memory ref size. 9534 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 9535 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 9536 uint32_t IncVal = CInc->getZExtValue(); 9537 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 9538 if (IsLaneOp || IsDupOp) 9539 NumBytes /= VecTy.getVectorNumElements(); 9540 if (IncVal != NumBytes) 9541 continue; 9542 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 9543 } 9544 SmallVector<SDValue, 8> Ops; 9545 Ops.push_back(N->getOperand(0)); // Incoming chain 9546 // Load lane and store have vector list as input. 9547 if (IsLaneOp || IsStore) 9548 for (unsigned i = 2; i < AddrOpIdx; ++i) 9549 Ops.push_back(N->getOperand(i)); 9550 Ops.push_back(Addr); // Base register 9551 Ops.push_back(Inc); 9552 9553 // Return Types. 9554 EVT Tys[6]; 9555 unsigned NumResultVecs = (IsStore ? 0 : NumVecs); 9556 unsigned n; 9557 for (n = 0; n < NumResultVecs; ++n) 9558 Tys[n] = VecTy; 9559 Tys[n++] = MVT::i64; // Type of write back register 9560 Tys[n] = MVT::Other; // Type of the chain 9561 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2)); 9562 9563 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N); 9564 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops, 9565 MemInt->getMemoryVT(), 9566 MemInt->getMemOperand()); 9567 9568 // Update the uses. 9569 std::vector<SDValue> NewResults; 9570 for (unsigned i = 0; i < NumResultVecs; ++i) { 9571 NewResults.push_back(SDValue(UpdN.getNode(), i)); 9572 } 9573 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); 9574 DCI.CombineTo(N, NewResults); 9575 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 9576 9577 break; 9578 } 9579 return SDValue(); 9580 } 9581 9582 // Checks to see if the value is the prescribed width and returns information 9583 // about its extension mode. 9584 static 9585 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) { 9586 ExtType = ISD::NON_EXTLOAD; 9587 switch(V.getNode()->getOpcode()) { 9588 default: 9589 return false; 9590 case ISD::LOAD: { 9591 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode()); 9592 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8) 9593 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) { 9594 ExtType = LoadNode->getExtensionType(); 9595 return true; 9596 } 9597 return false; 9598 } 9599 case ISD::AssertSext: { 9600 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 9601 if ((TypeNode->getVT() == MVT::i8 && width == 8) 9602 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 9603 ExtType = ISD::SEXTLOAD; 9604 return true; 9605 } 9606 return false; 9607 } 9608 case ISD::AssertZext: { 9609 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 9610 if ((TypeNode->getVT() == MVT::i8 && width == 8) 9611 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 9612 ExtType = ISD::ZEXTLOAD; 9613 return true; 9614 } 9615 return false; 9616 } 9617 case ISD::Constant: 9618 case ISD::TargetConstant: { 9619 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) < 9620 1LL << (width - 1); 9621 } 9622 } 9623 9624 return true; 9625 } 9626 9627 // This function does a whole lot of voodoo to determine if the tests are 9628 // equivalent without and with a mask. Essentially what happens is that given a 9629 // DAG resembling: 9630 // 9631 // +-------------+ +-------------+ +-------------+ +-------------+ 9632 // | Input | | AddConstant | | CompConstant| | CC | 9633 // +-------------+ +-------------+ +-------------+ +-------------+ 9634 // | | | | 9635 // V V | +----------+ 9636 // +-------------+ +----+ | | 9637 // | ADD | |0xff| | | 9638 // +-------------+ +----+ | | 9639 // | | | | 9640 // V V | | 9641 // +-------------+ | | 9642 // | AND | | | 9643 // +-------------+ | | 9644 // | | | 9645 // +-----+ | | 9646 // | | | 9647 // V V V 9648 // +-------------+ 9649 // | CMP | 9650 // +-------------+ 9651 // 9652 // The AND node may be safely removed for some combinations of inputs. In 9653 // particular we need to take into account the extension type of the Input, 9654 // the exact values of AddConstant, CompConstant, and CC, along with the nominal 9655 // width of the input (this can work for any width inputs, the above graph is 9656 // specific to 8 bits. 9657 // 9658 // The specific equations were worked out by generating output tables for each 9659 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The 9660 // problem was simplified by working with 4 bit inputs, which means we only 9661 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero 9662 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8 9663 // patterns present in both extensions (0,7). For every distinct set of 9664 // AddConstant and CompConstants bit patterns we can consider the masked and 9665 // unmasked versions to be equivalent if the result of this function is true for 9666 // all 16 distinct bit patterns of for the current extension type of Input (w0). 9667 // 9668 // sub w8, w0, w1 9669 // and w10, w8, #0x0f 9670 // cmp w8, w2 9671 // cset w9, AArch64CC 9672 // cmp w10, w2 9673 // cset w11, AArch64CC 9674 // cmp w9, w11 9675 // cset w0, eq 9676 // ret 9677 // 9678 // Since the above function shows when the outputs are equivalent it defines 9679 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and 9680 // would be expensive to run during compiles. The equations below were written 9681 // in a test harness that confirmed they gave equivalent outputs to the above 9682 // for all inputs function, so they can be used determine if the removal is 9683 // legal instead. 9684 // 9685 // isEquivalentMaskless() is the code for testing if the AND can be removed 9686 // factored out of the DAG recognition as the DAG can take several forms. 9687 9688 static bool isEquivalentMaskless(unsigned CC, unsigned width, 9689 ISD::LoadExtType ExtType, int AddConstant, 9690 int CompConstant) { 9691 // By being careful about our equations and only writing the in term 9692 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can 9693 // make them generally applicable to all bit widths. 9694 int MaxUInt = (1 << width); 9695 9696 // For the purposes of these comparisons sign extending the type is 9697 // equivalent to zero extending the add and displacing it by half the integer 9698 // width. Provided we are careful and make sure our equations are valid over 9699 // the whole range we can just adjust the input and avoid writing equations 9700 // for sign extended inputs. 9701 if (ExtType == ISD::SEXTLOAD) 9702 AddConstant -= (1 << (width-1)); 9703 9704 switch(CC) { 9705 case AArch64CC::LE: 9706 case AArch64CC::GT: { 9707 if ((AddConstant == 0) || 9708 (CompConstant == MaxUInt - 1 && AddConstant < 0) || 9709 (AddConstant >= 0 && CompConstant < 0) || 9710 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant)) 9711 return true; 9712 } break; 9713 case AArch64CC::LT: 9714 case AArch64CC::GE: { 9715 if ((AddConstant == 0) || 9716 (AddConstant >= 0 && CompConstant <= 0) || 9717 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant)) 9718 return true; 9719 } break; 9720 case AArch64CC::HI: 9721 case AArch64CC::LS: { 9722 if ((AddConstant >= 0 && CompConstant < 0) || 9723 (AddConstant <= 0 && CompConstant >= -1 && 9724 CompConstant < AddConstant + MaxUInt)) 9725 return true; 9726 } break; 9727 case AArch64CC::PL: 9728 case AArch64CC::MI: { 9729 if ((AddConstant == 0) || 9730 (AddConstant > 0 && CompConstant <= 0) || 9731 (AddConstant < 0 && CompConstant <= AddConstant)) 9732 return true; 9733 } break; 9734 case AArch64CC::LO: 9735 case AArch64CC::HS: { 9736 if ((AddConstant >= 0 && CompConstant <= 0) || 9737 (AddConstant <= 0 && CompConstant >= 0 && 9738 CompConstant <= AddConstant + MaxUInt)) 9739 return true; 9740 } break; 9741 case AArch64CC::EQ: 9742 case AArch64CC::NE: { 9743 if ((AddConstant > 0 && CompConstant < 0) || 9744 (AddConstant < 0 && CompConstant >= 0 && 9745 CompConstant < AddConstant + MaxUInt) || 9746 (AddConstant >= 0 && CompConstant >= 0 && 9747 CompConstant >= AddConstant) || 9748 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant)) 9749 9750 return true; 9751 } break; 9752 case AArch64CC::VS: 9753 case AArch64CC::VC: 9754 case AArch64CC::AL: 9755 case AArch64CC::NV: 9756 return true; 9757 case AArch64CC::Invalid: 9758 break; 9759 } 9760 9761 return false; 9762 } 9763 9764 static 9765 SDValue performCONDCombine(SDNode *N, 9766 TargetLowering::DAGCombinerInfo &DCI, 9767 SelectionDAG &DAG, unsigned CCIndex, 9768 unsigned CmpIndex) { 9769 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue(); 9770 SDNode *SubsNode = N->getOperand(CmpIndex).getNode(); 9771 unsigned CondOpcode = SubsNode->getOpcode(); 9772 9773 if (CondOpcode != AArch64ISD::SUBS) 9774 return SDValue(); 9775 9776 // There is a SUBS feeding this condition. Is it fed by a mask we can 9777 // use? 9778 9779 SDNode *AndNode = SubsNode->getOperand(0).getNode(); 9780 unsigned MaskBits = 0; 9781 9782 if (AndNode->getOpcode() != ISD::AND) 9783 return SDValue(); 9784 9785 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) { 9786 uint32_t CNV = CN->getZExtValue(); 9787 if (CNV == 255) 9788 MaskBits = 8; 9789 else if (CNV == 65535) 9790 MaskBits = 16; 9791 } 9792 9793 if (!MaskBits) 9794 return SDValue(); 9795 9796 SDValue AddValue = AndNode->getOperand(0); 9797 9798 if (AddValue.getOpcode() != ISD::ADD) 9799 return SDValue(); 9800 9801 // The basic dag structure is correct, grab the inputs and validate them. 9802 9803 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0); 9804 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1); 9805 SDValue SubsInputValue = SubsNode->getOperand(1); 9806 9807 // The mask is present and the provenance of all the values is a smaller type, 9808 // lets see if the mask is superfluous. 9809 9810 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) || 9811 !isa<ConstantSDNode>(SubsInputValue.getNode())) 9812 return SDValue(); 9813 9814 ISD::LoadExtType ExtType; 9815 9816 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) || 9817 !checkValueWidth(AddInputValue2, MaskBits, ExtType) || 9818 !checkValueWidth(AddInputValue1, MaskBits, ExtType) ) 9819 return SDValue(); 9820 9821 if(!isEquivalentMaskless(CC, MaskBits, ExtType, 9822 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(), 9823 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue())) 9824 return SDValue(); 9825 9826 // The AND is not necessary, remove it. 9827 9828 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0), 9829 SubsNode->getValueType(1)); 9830 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) }; 9831 9832 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops); 9833 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode()); 9834 9835 return SDValue(N, 0); 9836 } 9837 9838 // Optimize compare with zero and branch. 9839 static SDValue performBRCONDCombine(SDNode *N, 9840 TargetLowering::DAGCombinerInfo &DCI, 9841 SelectionDAG &DAG) { 9842 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3)) 9843 N = NV.getNode(); 9844 SDValue Chain = N->getOperand(0); 9845 SDValue Dest = N->getOperand(1); 9846 SDValue CCVal = N->getOperand(2); 9847 SDValue Cmp = N->getOperand(3); 9848 9849 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!"); 9850 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue(); 9851 if (CC != AArch64CC::EQ && CC != AArch64CC::NE) 9852 return SDValue(); 9853 9854 unsigned CmpOpc = Cmp.getOpcode(); 9855 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS) 9856 return SDValue(); 9857 9858 // Only attempt folding if there is only one use of the flag and no use of the 9859 // value. 9860 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1)) 9861 return SDValue(); 9862 9863 SDValue LHS = Cmp.getOperand(0); 9864 SDValue RHS = Cmp.getOperand(1); 9865 9866 assert(LHS.getValueType() == RHS.getValueType() && 9867 "Expected the value type to be the same for both operands!"); 9868 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 9869 return SDValue(); 9870 9871 if (isNullConstant(LHS)) 9872 std::swap(LHS, RHS); 9873 9874 if (!isNullConstant(RHS)) 9875 return SDValue(); 9876 9877 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA || 9878 LHS.getOpcode() == ISD::SRL) 9879 return SDValue(); 9880 9881 // Fold the compare into the branch instruction. 9882 SDValue BR; 9883 if (CC == AArch64CC::EQ) 9884 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 9885 else 9886 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 9887 9888 // Do not add new nodes to DAG combiner worklist. 9889 DCI.CombineTo(N, BR, false); 9890 9891 return SDValue(); 9892 } 9893 9894 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test 9895 // as well as whether the test should be inverted. This code is required to 9896 // catch these cases (as opposed to standard dag combines) because 9897 // AArch64ISD::TBZ is matched during legalization. 9898 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert, 9899 SelectionDAG &DAG) { 9900 9901 if (!Op->hasOneUse()) 9902 return Op; 9903 9904 // We don't handle undef/constant-fold cases below, as they should have 9905 // already been taken care of (e.g. and of 0, test of undefined shifted bits, 9906 // etc.) 9907 9908 // (tbz (trunc x), b) -> (tbz x, b) 9909 // This case is just here to enable more of the below cases to be caught. 9910 if (Op->getOpcode() == ISD::TRUNCATE && 9911 Bit < Op->getValueType(0).getSizeInBits()) { 9912 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 9913 } 9914 9915 if (Op->getNumOperands() != 2) 9916 return Op; 9917 9918 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 9919 if (!C) 9920 return Op; 9921 9922 switch (Op->getOpcode()) { 9923 default: 9924 return Op; 9925 9926 // (tbz (and x, m), b) -> (tbz x, b) 9927 case ISD::AND: 9928 if ((C->getZExtValue() >> Bit) & 1) 9929 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 9930 return Op; 9931 9932 // (tbz (shl x, c), b) -> (tbz x, b-c) 9933 case ISD::SHL: 9934 if (C->getZExtValue() <= Bit && 9935 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 9936 Bit = Bit - C->getZExtValue(); 9937 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 9938 } 9939 return Op; 9940 9941 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x 9942 case ISD::SRA: 9943 Bit = Bit + C->getZExtValue(); 9944 if (Bit >= Op->getValueType(0).getSizeInBits()) 9945 Bit = Op->getValueType(0).getSizeInBits() - 1; 9946 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 9947 9948 // (tbz (srl x, c), b) -> (tbz x, b+c) 9949 case ISD::SRL: 9950 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 9951 Bit = Bit + C->getZExtValue(); 9952 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 9953 } 9954 return Op; 9955 9956 // (tbz (xor x, -1), b) -> (tbnz x, b) 9957 case ISD::XOR: 9958 if ((C->getZExtValue() >> Bit) & 1) 9959 Invert = !Invert; 9960 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 9961 } 9962 } 9963 9964 // Optimize test single bit zero/non-zero and branch. 9965 static SDValue performTBZCombine(SDNode *N, 9966 TargetLowering::DAGCombinerInfo &DCI, 9967 SelectionDAG &DAG) { 9968 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 9969 bool Invert = false; 9970 SDValue TestSrc = N->getOperand(1); 9971 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG); 9972 9973 if (TestSrc == NewTestSrc) 9974 return SDValue(); 9975 9976 unsigned NewOpc = N->getOpcode(); 9977 if (Invert) { 9978 if (NewOpc == AArch64ISD::TBZ) 9979 NewOpc = AArch64ISD::TBNZ; 9980 else { 9981 assert(NewOpc == AArch64ISD::TBNZ); 9982 NewOpc = AArch64ISD::TBZ; 9983 } 9984 } 9985 9986 SDLoc DL(N); 9987 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc, 9988 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3)); 9989 } 9990 9991 // vselect (v1i1 setcc) -> 9992 // vselect (v1iXX setcc) (XX is the size of the compared operand type) 9993 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as 9994 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine 9995 // such VSELECT. 9996 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) { 9997 SDValue N0 = N->getOperand(0); 9998 EVT CCVT = N0.getValueType(); 9999 10000 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 || 10001 CCVT.getVectorElementType() != MVT::i1) 10002 return SDValue(); 10003 10004 EVT ResVT = N->getValueType(0); 10005 EVT CmpVT = N0.getOperand(0).getValueType(); 10006 // Only combine when the result type is of the same size as the compared 10007 // operands. 10008 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits()) 10009 return SDValue(); 10010 10011 SDValue IfTrue = N->getOperand(1); 10012 SDValue IfFalse = N->getOperand(2); 10013 SDValue SetCC = 10014 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(), 10015 N0.getOperand(0), N0.getOperand(1), 10016 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 10017 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC, 10018 IfTrue, IfFalse); 10019 } 10020 10021 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with 10022 /// the compare-mask instructions rather than going via NZCV, even if LHS and 10023 /// RHS are really scalar. This replaces any scalar setcc in the above pattern 10024 /// with a vector one followed by a DUP shuffle on the result. 10025 static SDValue performSelectCombine(SDNode *N, 10026 TargetLowering::DAGCombinerInfo &DCI) { 10027 SelectionDAG &DAG = DCI.DAG; 10028 SDValue N0 = N->getOperand(0); 10029 EVT ResVT = N->getValueType(0); 10030 10031 if (N0.getOpcode() != ISD::SETCC) 10032 return SDValue(); 10033 10034 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered 10035 // scalar SetCCResultType. We also don't expect vectors, because we assume 10036 // that selects fed by vector SETCCs are canonicalized to VSELECT. 10037 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) && 10038 "Scalar-SETCC feeding SELECT has unexpected result type!"); 10039 10040 // If NumMaskElts == 0, the comparison is larger than select result. The 10041 // largest real NEON comparison is 64-bits per lane, which means the result is 10042 // at most 32-bits and an illegal vector. Just bail out for now. 10043 EVT SrcVT = N0.getOperand(0).getValueType(); 10044 10045 // Don't try to do this optimization when the setcc itself has i1 operands. 10046 // There are no legal vectors of i1, so this would be pointless. 10047 if (SrcVT == MVT::i1) 10048 return SDValue(); 10049 10050 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits(); 10051 if (!ResVT.isVector() || NumMaskElts == 0) 10052 return SDValue(); 10053 10054 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts); 10055 EVT CCVT = SrcVT.changeVectorElementTypeToInteger(); 10056 10057 // Also bail out if the vector CCVT isn't the same size as ResVT. 10058 // This can happen if the SETCC operand size doesn't divide the ResVT size 10059 // (e.g., f64 vs v3f32). 10060 if (CCVT.getSizeInBits() != ResVT.getSizeInBits()) 10061 return SDValue(); 10062 10063 // Make sure we didn't create illegal types, if we're not supposed to. 10064 assert(DCI.isBeforeLegalize() || 10065 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT)); 10066 10067 // First perform a vector comparison, where lane 0 is the one we're interested 10068 // in. 10069 SDLoc DL(N0); 10070 SDValue LHS = 10071 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0)); 10072 SDValue RHS = 10073 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1)); 10074 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2)); 10075 10076 // Now duplicate the comparison mask we want across all other lanes. 10077 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0); 10078 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask); 10079 Mask = DAG.getNode(ISD::BITCAST, DL, 10080 ResVT.changeVectorElementTypeToInteger(), Mask); 10081 10082 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2)); 10083 } 10084 10085 /// Get rid of unnecessary NVCASTs (that don't change the type). 10086 static SDValue performNVCASTCombine(SDNode *N) { 10087 if (N->getValueType(0) == N->getOperand(0).getValueType()) 10088 return N->getOperand(0); 10089 10090 return SDValue(); 10091 } 10092 10093 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N, 10094 DAGCombinerInfo &DCI) const { 10095 SelectionDAG &DAG = DCI.DAG; 10096 switch (N->getOpcode()) { 10097 default: 10098 break; 10099 case ISD::ADD: 10100 case ISD::SUB: 10101 return performAddSubLongCombine(N, DCI, DAG); 10102 case ISD::XOR: 10103 return performXorCombine(N, DAG, DCI, Subtarget); 10104 case ISD::MUL: 10105 return performMulCombine(N, DAG, DCI, Subtarget); 10106 case ISD::SINT_TO_FP: 10107 case ISD::UINT_TO_FP: 10108 return performIntToFpCombine(N, DAG, Subtarget); 10109 case ISD::FP_TO_SINT: 10110 case ISD::FP_TO_UINT: 10111 return performFpToIntCombine(N, DAG, DCI, Subtarget); 10112 case ISD::FDIV: 10113 return performFDivCombine(N, DAG, DCI, Subtarget); 10114 case ISD::OR: 10115 return performORCombine(N, DCI, Subtarget); 10116 case ISD::SRL: 10117 return performSRLCombine(N, DCI); 10118 case ISD::INTRINSIC_WO_CHAIN: 10119 return performIntrinsicCombine(N, DCI, Subtarget); 10120 case ISD::ANY_EXTEND: 10121 case ISD::ZERO_EXTEND: 10122 case ISD::SIGN_EXTEND: 10123 return performExtendCombine(N, DCI, DAG); 10124 case ISD::BITCAST: 10125 return performBitcastCombine(N, DCI, DAG); 10126 case ISD::CONCAT_VECTORS: 10127 return performConcatVectorsCombine(N, DCI, DAG); 10128 case ISD::SELECT: { 10129 SDValue RV = performSelectCombine(N, DCI); 10130 if (!RV.getNode()) 10131 RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget); 10132 return RV; 10133 } 10134 case ISD::VSELECT: 10135 return performVSelectCombine(N, DCI.DAG); 10136 case ISD::LOAD: 10137 if (performTBISimplification(N->getOperand(1), DCI, DAG)) 10138 return SDValue(N, 0); 10139 break; 10140 case ISD::STORE: 10141 return performSTORECombine(N, DCI, DAG, Subtarget); 10142 case AArch64ISD::BRCOND: 10143 return performBRCONDCombine(N, DCI, DAG); 10144 case AArch64ISD::TBNZ: 10145 case AArch64ISD::TBZ: 10146 return performTBZCombine(N, DCI, DAG); 10147 case AArch64ISD::CSEL: 10148 return performCONDCombine(N, DCI, DAG, 2, 3); 10149 case AArch64ISD::DUP: 10150 return performPostLD1Combine(N, DCI, false); 10151 case AArch64ISD::NVCAST: 10152 return performNVCASTCombine(N); 10153 case ISD::INSERT_VECTOR_ELT: 10154 return performPostLD1Combine(N, DCI, true); 10155 case ISD::EXTRACT_VECTOR_ELT: 10156 return performAcrossLaneAddReductionCombine(N, DAG, Subtarget); 10157 case ISD::INTRINSIC_VOID: 10158 case ISD::INTRINSIC_W_CHAIN: 10159 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 10160 case Intrinsic::aarch64_neon_ld2: 10161 case Intrinsic::aarch64_neon_ld3: 10162 case Intrinsic::aarch64_neon_ld4: 10163 case Intrinsic::aarch64_neon_ld1x2: 10164 case Intrinsic::aarch64_neon_ld1x3: 10165 case Intrinsic::aarch64_neon_ld1x4: 10166 case Intrinsic::aarch64_neon_ld2lane: 10167 case Intrinsic::aarch64_neon_ld3lane: 10168 case Intrinsic::aarch64_neon_ld4lane: 10169 case Intrinsic::aarch64_neon_ld2r: 10170 case Intrinsic::aarch64_neon_ld3r: 10171 case Intrinsic::aarch64_neon_ld4r: 10172 case Intrinsic::aarch64_neon_st2: 10173 case Intrinsic::aarch64_neon_st3: 10174 case Intrinsic::aarch64_neon_st4: 10175 case Intrinsic::aarch64_neon_st1x2: 10176 case Intrinsic::aarch64_neon_st1x3: 10177 case Intrinsic::aarch64_neon_st1x4: 10178 case Intrinsic::aarch64_neon_st2lane: 10179 case Intrinsic::aarch64_neon_st3lane: 10180 case Intrinsic::aarch64_neon_st4lane: 10181 return performNEONPostLDSTCombine(N, DCI, DAG); 10182 default: 10183 break; 10184 } 10185 } 10186 return SDValue(); 10187 } 10188 10189 // Check if the return value is used as only a return value, as otherwise 10190 // we can't perform a tail-call. In particular, we need to check for 10191 // target ISD nodes that are returns and any other "odd" constructs 10192 // that the generic analysis code won't necessarily catch. 10193 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N, 10194 SDValue &Chain) const { 10195 if (N->getNumValues() != 1) 10196 return false; 10197 if (!N->hasNUsesOfValue(1, 0)) 10198 return false; 10199 10200 SDValue TCChain = Chain; 10201 SDNode *Copy = *N->use_begin(); 10202 if (Copy->getOpcode() == ISD::CopyToReg) { 10203 // If the copy has a glue operand, we conservatively assume it isn't safe to 10204 // perform a tail call. 10205 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() == 10206 MVT::Glue) 10207 return false; 10208 TCChain = Copy->getOperand(0); 10209 } else if (Copy->getOpcode() != ISD::FP_EXTEND) 10210 return false; 10211 10212 bool HasRet = false; 10213 for (SDNode *Node : Copy->uses()) { 10214 if (Node->getOpcode() != AArch64ISD::RET_FLAG) 10215 return false; 10216 HasRet = true; 10217 } 10218 10219 if (!HasRet) 10220 return false; 10221 10222 Chain = TCChain; 10223 return true; 10224 } 10225 10226 // Return whether the an instruction can potentially be optimized to a tail 10227 // call. This will cause the optimizers to attempt to move, or duplicate, 10228 // return instructions to help enable tail call optimizations for this 10229 // instruction. 10230 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const { 10231 return CI->isTailCall(); 10232 } 10233 10234 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base, 10235 SDValue &Offset, 10236 ISD::MemIndexedMode &AM, 10237 bool &IsInc, 10238 SelectionDAG &DAG) const { 10239 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) 10240 return false; 10241 10242 Base = Op->getOperand(0); 10243 // All of the indexed addressing mode instructions take a signed 10244 // 9 bit immediate offset. 10245 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) { 10246 int64_t RHSC = (int64_t)RHS->getZExtValue(); 10247 if (RHSC >= 256 || RHSC <= -256) 10248 return false; 10249 IsInc = (Op->getOpcode() == ISD::ADD); 10250 Offset = Op->getOperand(1); 10251 return true; 10252 } 10253 return false; 10254 } 10255 10256 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 10257 SDValue &Offset, 10258 ISD::MemIndexedMode &AM, 10259 SelectionDAG &DAG) const { 10260 EVT VT; 10261 SDValue Ptr; 10262 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10263 VT = LD->getMemoryVT(); 10264 Ptr = LD->getBasePtr(); 10265 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10266 VT = ST->getMemoryVT(); 10267 Ptr = ST->getBasePtr(); 10268 } else 10269 return false; 10270 10271 bool IsInc; 10272 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG)) 10273 return false; 10274 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC; 10275 return true; 10276 } 10277 10278 bool AArch64TargetLowering::getPostIndexedAddressParts( 10279 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset, 10280 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const { 10281 EVT VT; 10282 SDValue Ptr; 10283 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 10284 VT = LD->getMemoryVT(); 10285 Ptr = LD->getBasePtr(); 10286 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 10287 VT = ST->getMemoryVT(); 10288 Ptr = ST->getBasePtr(); 10289 } else 10290 return false; 10291 10292 bool IsInc; 10293 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG)) 10294 return false; 10295 // Post-indexing updates the base, so it's not a valid transform 10296 // if that's not the same as the load's pointer. 10297 if (Ptr != Base) 10298 return false; 10299 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC; 10300 return true; 10301 } 10302 10303 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results, 10304 SelectionDAG &DAG) { 10305 SDLoc DL(N); 10306 SDValue Op = N->getOperand(0); 10307 10308 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16) 10309 return; 10310 10311 Op = SDValue( 10312 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32, 10313 DAG.getUNDEF(MVT::i32), Op, 10314 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 10315 0); 10316 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op); 10317 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op)); 10318 } 10319 10320 static void ReplaceReductionResults(SDNode *N, 10321 SmallVectorImpl<SDValue> &Results, 10322 SelectionDAG &DAG, unsigned InterOp, 10323 unsigned AcrossOp) { 10324 EVT LoVT, HiVT; 10325 SDValue Lo, Hi; 10326 SDLoc dl(N); 10327 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 10328 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0); 10329 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi); 10330 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal); 10331 Results.push_back(SplitVal); 10332 } 10333 10334 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) { 10335 SDLoc DL(N); 10336 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N); 10337 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, 10338 DAG.getNode(ISD::SRL, DL, MVT::i128, N, 10339 DAG.getConstant(64, DL, MVT::i64))); 10340 return std::make_pair(Lo, Hi); 10341 } 10342 10343 static void ReplaceCMP_SWAP_128Results(SDNode *N, 10344 SmallVectorImpl<SDValue> & Results, 10345 SelectionDAG &DAG) { 10346 assert(N->getValueType(0) == MVT::i128 && 10347 "AtomicCmpSwap on types less than 128 should be legal"); 10348 auto Desired = splitInt128(N->getOperand(2), DAG); 10349 auto New = splitInt128(N->getOperand(3), DAG); 10350 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second, 10351 New.first, New.second, N->getOperand(0)}; 10352 SDNode *CmpSwap = DAG.getMachineNode( 10353 AArch64::CMP_SWAP_128, SDLoc(N), 10354 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops); 10355 10356 MachineFunction &MF = DAG.getMachineFunction(); 10357 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1); 10358 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 10359 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1); 10360 10361 Results.push_back(SDValue(CmpSwap, 0)); 10362 Results.push_back(SDValue(CmpSwap, 1)); 10363 Results.push_back(SDValue(CmpSwap, 3)); 10364 } 10365 10366 void AArch64TargetLowering::ReplaceNodeResults( 10367 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const { 10368 switch (N->getOpcode()) { 10369 default: 10370 llvm_unreachable("Don't know how to custom expand this"); 10371 case ISD::BITCAST: 10372 ReplaceBITCASTResults(N, Results, DAG); 10373 return; 10374 case AArch64ISD::SADDV: 10375 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV); 10376 return; 10377 case AArch64ISD::UADDV: 10378 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV); 10379 return; 10380 case AArch64ISD::SMINV: 10381 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV); 10382 return; 10383 case AArch64ISD::UMINV: 10384 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV); 10385 return; 10386 case AArch64ISD::SMAXV: 10387 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV); 10388 return; 10389 case AArch64ISD::UMAXV: 10390 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV); 10391 return; 10392 case ISD::FP_TO_UINT: 10393 case ISD::FP_TO_SINT: 10394 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion"); 10395 // Let normal code take care of it by not adding anything to Results. 10396 return; 10397 case ISD::ATOMIC_CMP_SWAP: 10398 ReplaceCMP_SWAP_128Results(N, Results, DAG); 10399 return; 10400 } 10401 } 10402 10403 bool AArch64TargetLowering::useLoadStackGuardNode() const { 10404 if (!Subtarget->isTargetAndroid()) 10405 return true; 10406 return TargetLowering::useLoadStackGuardNode(); 10407 } 10408 10409 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const { 10410 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 10411 // reciprocal if there are three or more FDIVs. 10412 return 3; 10413 } 10414 10415 TargetLoweringBase::LegalizeTypeAction 10416 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const { 10417 MVT SVT = VT.getSimpleVT(); 10418 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8, 10419 // v4i16, v2i32 instead of to promote. 10420 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32 10421 || SVT == MVT::v1f32) 10422 return TypeWidenVector; 10423 10424 return TargetLoweringBase::getPreferredVectorAction(VT); 10425 } 10426 10427 // Loads and stores less than 128-bits are already atomic; ones above that 10428 // are doomed anyway, so defer to the default libcall and blame the OS when 10429 // things go wrong. 10430 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 10431 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 10432 return Size == 128; 10433 } 10434 10435 // Loads and stores less than 128-bits are already atomic; ones above that 10436 // are doomed anyway, so defer to the default libcall and blame the OS when 10437 // things go wrong. 10438 TargetLowering::AtomicExpansionKind 10439 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 10440 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 10441 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None; 10442 } 10443 10444 // For the real atomic operations, we have ldxr/stxr up to 128 bits, 10445 TargetLowering::AtomicExpansionKind 10446 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 10447 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 10448 return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None; 10449 } 10450 10451 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR( 10452 AtomicCmpXchgInst *AI) const { 10453 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 10454 // implement cmpxchg without spilling. If the address being exchanged is also 10455 // on the stack and close enough to the spill slot, this can lead to a 10456 // situation where the monitor always gets cleared and the atomic operation 10457 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 10458 return getTargetMachine().getOptLevel() != 0; 10459 } 10460 10461 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 10462 AtomicOrdering Ord) const { 10463 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10464 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 10465 bool IsAcquire = isAcquireOrStronger(Ord); 10466 10467 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd 10468 // intrinsic must return {i64, i64} and we have to recombine them into a 10469 // single i128 here. 10470 if (ValTy->getPrimitiveSizeInBits() == 128) { 10471 Intrinsic::ID Int = 10472 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp; 10473 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int); 10474 10475 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 10476 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi"); 10477 10478 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 10479 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 10480 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 10481 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 10482 return Builder.CreateOr( 10483 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 10484 } 10485 10486 Type *Tys[] = { Addr->getType() }; 10487 Intrinsic::ID Int = 10488 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr; 10489 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys); 10490 10491 return Builder.CreateTruncOrBitCast( 10492 Builder.CreateCall(Ldxr, Addr), 10493 cast<PointerType>(Addr->getType())->getElementType()); 10494 } 10495 10496 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 10497 IRBuilder<> &Builder) const { 10498 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10499 Builder.CreateCall( 10500 llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex)); 10501 } 10502 10503 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder, 10504 Value *Val, Value *Addr, 10505 AtomicOrdering Ord) const { 10506 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 10507 bool IsRelease = isReleaseOrStronger(Ord); 10508 10509 // Since the intrinsics must have legal type, the i128 intrinsics take two 10510 // parameters: "i64, i64". We must marshal Val into the appropriate form 10511 // before the call. 10512 if (Val->getType()->getPrimitiveSizeInBits() == 128) { 10513 Intrinsic::ID Int = 10514 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp; 10515 Function *Stxr = Intrinsic::getDeclaration(M, Int); 10516 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 10517 10518 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo"); 10519 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi"); 10520 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 10521 return Builder.CreateCall(Stxr, {Lo, Hi, Addr}); 10522 } 10523 10524 Intrinsic::ID Int = 10525 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr; 10526 Type *Tys[] = { Addr->getType() }; 10527 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys); 10528 10529 return Builder.CreateCall(Stxr, 10530 {Builder.CreateZExtOrBitCast( 10531 Val, Stxr->getFunctionType()->getParamType(0)), 10532 Addr}); 10533 } 10534 10535 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters( 10536 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 10537 return Ty->isArrayTy(); 10538 } 10539 10540 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &, 10541 EVT) const { 10542 return false; 10543 } 10544 10545 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const { 10546 if (!Subtarget->isTargetAndroid()) 10547 return TargetLowering::getIRStackGuard(IRB); 10548 10549 // Android provides a fixed TLS slot for the stack cookie. See the definition 10550 // of TLS_SLOT_STACK_GUARD in 10551 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 10552 const unsigned TlsOffset = 0x28; 10553 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 10554 Function *ThreadPointerFunc = 10555 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer); 10556 return IRB.CreatePointerCast( 10557 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset), 10558 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0)); 10559 } 10560 10561 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const { 10562 if (!Subtarget->isTargetAndroid()) 10563 return TargetLowering::getSafeStackPointerLocation(IRB); 10564 10565 // Android provides a fixed TLS slot for the SafeStack pointer. See the 10566 // definition of TLS_SLOT_SAFESTACK in 10567 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 10568 const unsigned TlsOffset = 0x48; 10569 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 10570 Function *ThreadPointerFunc = 10571 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer); 10572 return IRB.CreatePointerCast( 10573 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset), 10574 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0)); 10575 } 10576 10577 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 10578 // Update IsSplitCSR in AArch64unctionInfo. 10579 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>(); 10580 AFI->setIsSplitCSR(true); 10581 } 10582 10583 void AArch64TargetLowering::insertCopiesSplitCSR( 10584 MachineBasicBlock *Entry, 10585 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 10586 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 10587 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 10588 if (!IStart) 10589 return; 10590 10591 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 10592 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 10593 MachineBasicBlock::iterator MBBI = Entry->begin(); 10594 for (const MCPhysReg *I = IStart; *I; ++I) { 10595 const TargetRegisterClass *RC = nullptr; 10596 if (AArch64::GPR64RegClass.contains(*I)) 10597 RC = &AArch64::GPR64RegClass; 10598 else if (AArch64::FPR64RegClass.contains(*I)) 10599 RC = &AArch64::FPR64RegClass; 10600 else 10601 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 10602 10603 unsigned NewVR = MRI->createVirtualRegister(RC); 10604 // Create copy from CSR to a virtual register. 10605 // FIXME: this currently does not emit CFI pseudo-instructions, it works 10606 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 10607 // nounwind. If we want to generalize this later, we may need to emit 10608 // CFI pseudo-instructions. 10609 assert(Entry->getParent()->getFunction()->hasFnAttribute( 10610 Attribute::NoUnwind) && 10611 "Function should be nounwind in insertCopiesSplitCSR!"); 10612 Entry->addLiveIn(*I); 10613 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 10614 .addReg(*I); 10615 10616 // Insert the copy-back instructions right before the terminator. 10617 for (auto *Exit : Exits) 10618 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 10619 TII->get(TargetOpcode::COPY), *I) 10620 .addReg(NewVR); 10621 } 10622 } 10623 10624 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const { 10625 // Integer division on AArch64 is expensive. However, when aggressively 10626 // optimizing for code size, we prefer to use a div instruction, as it is 10627 // usually smaller than the alternative sequence. 10628 // The exception to this is vector division. Since AArch64 doesn't have vector 10629 // integer division, leaving the division as-is is a loss even in terms of 10630 // size, because it will have to be scalarized, while the alternative code 10631 // sequence can be performed in vector form. 10632 bool OptSize = 10633 Attr.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize); 10634 return OptSize && !VT.isVector(); 10635 } 10636