1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the AArch64TargetLowering class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "AArch64ExpandImm.h" 14 #include "AArch64ISelLowering.h" 15 #include "AArch64CallingConvention.h" 16 #include "AArch64MachineFunctionInfo.h" 17 #include "AArch64PerfectShuffle.h" 18 #include "AArch64RegisterInfo.h" 19 #include "AArch64Subtarget.h" 20 #include "MCTargetDesc/AArch64AddressingModes.h" 21 #include "Utils/AArch64BaseInfo.h" 22 #include "llvm/ADT/APFloat.h" 23 #include "llvm/ADT/APInt.h" 24 #include "llvm/ADT/ArrayRef.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/SmallVector.h" 27 #include "llvm/ADT/Statistic.h" 28 #include "llvm/ADT/StringRef.h" 29 #include "llvm/ADT/StringSwitch.h" 30 #include "llvm/ADT/Triple.h" 31 #include "llvm/ADT/Twine.h" 32 #include "llvm/Analysis/VectorUtils.h" 33 #include "llvm/CodeGen/CallingConvLower.h" 34 #include "llvm/CodeGen/MachineBasicBlock.h" 35 #include "llvm/CodeGen/MachineFrameInfo.h" 36 #include "llvm/CodeGen/MachineFunction.h" 37 #include "llvm/CodeGen/MachineInstr.h" 38 #include "llvm/CodeGen/MachineInstrBuilder.h" 39 #include "llvm/CodeGen/MachineMemOperand.h" 40 #include "llvm/CodeGen/MachineRegisterInfo.h" 41 #include "llvm/CodeGen/RuntimeLibcalls.h" 42 #include "llvm/CodeGen/SelectionDAG.h" 43 #include "llvm/CodeGen/SelectionDAGNodes.h" 44 #include "llvm/CodeGen/TargetCallingConv.h" 45 #include "llvm/CodeGen/TargetInstrInfo.h" 46 #include "llvm/CodeGen/ValueTypes.h" 47 #include "llvm/IR/Attributes.h" 48 #include "llvm/IR/Constants.h" 49 #include "llvm/IR/DataLayout.h" 50 #include "llvm/IR/DebugLoc.h" 51 #include "llvm/IR/DerivedTypes.h" 52 #include "llvm/IR/Function.h" 53 #include "llvm/IR/GetElementPtrTypeIterator.h" 54 #include "llvm/IR/GlobalValue.h" 55 #include "llvm/IR/IRBuilder.h" 56 #include "llvm/IR/Instruction.h" 57 #include "llvm/IR/Instructions.h" 58 #include "llvm/IR/IntrinsicInst.h" 59 #include "llvm/IR/Intrinsics.h" 60 #include "llvm/IR/Module.h" 61 #include "llvm/IR/OperandTraits.h" 62 #include "llvm/IR/PatternMatch.h" 63 #include "llvm/IR/Type.h" 64 #include "llvm/IR/Use.h" 65 #include "llvm/IR/Value.h" 66 #include "llvm/MC/MCRegisterInfo.h" 67 #include "llvm/Support/Casting.h" 68 #include "llvm/Support/CodeGen.h" 69 #include "llvm/Support/CommandLine.h" 70 #include "llvm/Support/Compiler.h" 71 #include "llvm/Support/Debug.h" 72 #include "llvm/Support/ErrorHandling.h" 73 #include "llvm/Support/KnownBits.h" 74 #include "llvm/Support/MachineValueType.h" 75 #include "llvm/Support/MathExtras.h" 76 #include "llvm/Support/raw_ostream.h" 77 #include "llvm/Target/TargetMachine.h" 78 #include "llvm/Target/TargetOptions.h" 79 #include <algorithm> 80 #include <bitset> 81 #include <cassert> 82 #include <cctype> 83 #include <cstdint> 84 #include <cstdlib> 85 #include <iterator> 86 #include <limits> 87 #include <tuple> 88 #include <utility> 89 #include <vector> 90 91 using namespace llvm; 92 using namespace llvm::PatternMatch; 93 94 #define DEBUG_TYPE "aarch64-lower" 95 96 STATISTIC(NumTailCalls, "Number of tail calls"); 97 STATISTIC(NumShiftInserts, "Number of vector shift inserts"); 98 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized"); 99 100 static cl::opt<bool> 101 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden, 102 cl::desc("Allow AArch64 SLI/SRI formation"), 103 cl::init(false)); 104 105 // FIXME: The necessary dtprel relocations don't seem to be supported 106 // well in the GNU bfd and gold linkers at the moment. Therefore, by 107 // default, for now, fall back to GeneralDynamic code generation. 108 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration( 109 "aarch64-elf-ldtls-generation", cl::Hidden, 110 cl::desc("Allow AArch64 Local Dynamic TLS code generation"), 111 cl::init(false)); 112 113 static cl::opt<bool> 114 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden, 115 cl::desc("Enable AArch64 logical imm instruction " 116 "optimization"), 117 cl::init(true)); 118 119 /// Value type used for condition codes. 120 static const MVT MVT_CC = MVT::i32; 121 122 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM, 123 const AArch64Subtarget &STI) 124 : TargetLowering(TM), Subtarget(&STI) { 125 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so 126 // we have to make something up. Arbitrarily, choose ZeroOrOne. 127 setBooleanContents(ZeroOrOneBooleanContent); 128 // When comparing vectors the result sets the different elements in the 129 // vector to all-one or all-zero. 130 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent); 131 132 // Set up the register classes. 133 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass); 134 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass); 135 136 if (Subtarget->hasFPARMv8()) { 137 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass); 138 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass); 139 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass); 140 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass); 141 } 142 143 if (Subtarget->hasNEON()) { 144 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass); 145 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass); 146 // Someone set us up the NEON. 147 addDRTypeForNEON(MVT::v2f32); 148 addDRTypeForNEON(MVT::v8i8); 149 addDRTypeForNEON(MVT::v4i16); 150 addDRTypeForNEON(MVT::v2i32); 151 addDRTypeForNEON(MVT::v1i64); 152 addDRTypeForNEON(MVT::v1f64); 153 addDRTypeForNEON(MVT::v4f16); 154 155 addQRTypeForNEON(MVT::v4f32); 156 addQRTypeForNEON(MVT::v2f64); 157 addQRTypeForNEON(MVT::v16i8); 158 addQRTypeForNEON(MVT::v8i16); 159 addQRTypeForNEON(MVT::v4i32); 160 addQRTypeForNEON(MVT::v2i64); 161 addQRTypeForNEON(MVT::v8f16); 162 } 163 164 // Compute derived properties from the register classes 165 computeRegisterProperties(Subtarget->getRegisterInfo()); 166 167 // Provide all sorts of operation actions 168 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom); 169 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom); 170 setOperationAction(ISD::SETCC, MVT::i32, Custom); 171 setOperationAction(ISD::SETCC, MVT::i64, Custom); 172 setOperationAction(ISD::SETCC, MVT::f16, Custom); 173 setOperationAction(ISD::SETCC, MVT::f32, Custom); 174 setOperationAction(ISD::SETCC, MVT::f64, Custom); 175 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal); 176 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal); 177 setOperationAction(ISD::BRCOND, MVT::Other, Expand); 178 setOperationAction(ISD::BR_CC, MVT::i32, Custom); 179 setOperationAction(ISD::BR_CC, MVT::i64, Custom); 180 setOperationAction(ISD::BR_CC, MVT::f16, Custom); 181 setOperationAction(ISD::BR_CC, MVT::f32, Custom); 182 setOperationAction(ISD::BR_CC, MVT::f64, Custom); 183 setOperationAction(ISD::SELECT, MVT::i32, Custom); 184 setOperationAction(ISD::SELECT, MVT::i64, Custom); 185 setOperationAction(ISD::SELECT, MVT::f16, Custom); 186 setOperationAction(ISD::SELECT, MVT::f32, Custom); 187 setOperationAction(ISD::SELECT, MVT::f64, Custom); 188 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom); 189 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom); 190 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom); 191 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom); 192 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom); 193 setOperationAction(ISD::BR_JT, MVT::Other, Custom); 194 setOperationAction(ISD::JumpTable, MVT::i64, Custom); 195 196 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom); 197 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom); 198 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom); 199 200 setOperationAction(ISD::FREM, MVT::f32, Expand); 201 setOperationAction(ISD::FREM, MVT::f64, Expand); 202 setOperationAction(ISD::FREM, MVT::f80, Expand); 203 204 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand); 205 206 // Custom lowering hooks are needed for XOR 207 // to fold it into CSINC/CSINV. 208 setOperationAction(ISD::XOR, MVT::i32, Custom); 209 setOperationAction(ISD::XOR, MVT::i64, Custom); 210 211 // Virtually no operation on f128 is legal, but LLVM can't expand them when 212 // there's a valid register class, so we need custom operations in most cases. 213 setOperationAction(ISD::FABS, MVT::f128, Expand); 214 setOperationAction(ISD::FADD, MVT::f128, Custom); 215 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand); 216 setOperationAction(ISD::FCOS, MVT::f128, Expand); 217 setOperationAction(ISD::FDIV, MVT::f128, Custom); 218 setOperationAction(ISD::FMA, MVT::f128, Expand); 219 setOperationAction(ISD::FMUL, MVT::f128, Custom); 220 setOperationAction(ISD::FNEG, MVT::f128, Expand); 221 setOperationAction(ISD::FPOW, MVT::f128, Expand); 222 setOperationAction(ISD::FREM, MVT::f128, Expand); 223 setOperationAction(ISD::FRINT, MVT::f128, Expand); 224 setOperationAction(ISD::FSIN, MVT::f128, Expand); 225 setOperationAction(ISD::FSINCOS, MVT::f128, Expand); 226 setOperationAction(ISD::FSQRT, MVT::f128, Expand); 227 setOperationAction(ISD::FSUB, MVT::f128, Custom); 228 setOperationAction(ISD::FTRUNC, MVT::f128, Expand); 229 setOperationAction(ISD::SETCC, MVT::f128, Custom); 230 setOperationAction(ISD::BR_CC, MVT::f128, Custom); 231 setOperationAction(ISD::SELECT, MVT::f128, Custom); 232 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom); 233 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom); 234 235 // Lowering for many of the conversions is actually specified by the non-f128 236 // type. The LowerXXX function will be trivial when f128 isn't involved. 237 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom); 238 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom); 239 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom); 240 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom); 241 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom); 242 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom); 243 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom); 244 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom); 245 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom); 246 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom); 247 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom); 248 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom); 249 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom); 250 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom); 251 252 // Variable arguments. 253 setOperationAction(ISD::VASTART, MVT::Other, Custom); 254 setOperationAction(ISD::VAARG, MVT::Other, Custom); 255 setOperationAction(ISD::VACOPY, MVT::Other, Custom); 256 setOperationAction(ISD::VAEND, MVT::Other, Expand); 257 258 // Variable-sized objects. 259 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand); 260 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand); 261 262 if (Subtarget->isTargetWindows()) 263 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom); 264 else 265 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand); 266 267 // Constant pool entries 268 setOperationAction(ISD::ConstantPool, MVT::i64, Custom); 269 270 // BlockAddress 271 setOperationAction(ISD::BlockAddress, MVT::i64, Custom); 272 273 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences. 274 setOperationAction(ISD::ADDC, MVT::i32, Custom); 275 setOperationAction(ISD::ADDE, MVT::i32, Custom); 276 setOperationAction(ISD::SUBC, MVT::i32, Custom); 277 setOperationAction(ISD::SUBE, MVT::i32, Custom); 278 setOperationAction(ISD::ADDC, MVT::i64, Custom); 279 setOperationAction(ISD::ADDE, MVT::i64, Custom); 280 setOperationAction(ISD::SUBC, MVT::i64, Custom); 281 setOperationAction(ISD::SUBE, MVT::i64, Custom); 282 283 // AArch64 lacks both left-rotate and popcount instructions. 284 setOperationAction(ISD::ROTL, MVT::i32, Expand); 285 setOperationAction(ISD::ROTL, MVT::i64, Expand); 286 for (MVT VT : MVT::vector_valuetypes()) { 287 setOperationAction(ISD::ROTL, VT, Expand); 288 setOperationAction(ISD::ROTR, VT, Expand); 289 } 290 291 // AArch64 doesn't have {U|S}MUL_LOHI. 292 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand); 293 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand); 294 295 setOperationAction(ISD::CTPOP, MVT::i32, Custom); 296 setOperationAction(ISD::CTPOP, MVT::i64, Custom); 297 298 setOperationAction(ISD::SDIVREM, MVT::i32, Expand); 299 setOperationAction(ISD::SDIVREM, MVT::i64, Expand); 300 for (MVT VT : MVT::vector_valuetypes()) { 301 setOperationAction(ISD::SDIVREM, VT, Expand); 302 setOperationAction(ISD::UDIVREM, VT, Expand); 303 } 304 setOperationAction(ISD::SREM, MVT::i32, Expand); 305 setOperationAction(ISD::SREM, MVT::i64, Expand); 306 setOperationAction(ISD::UDIVREM, MVT::i32, Expand); 307 setOperationAction(ISD::UDIVREM, MVT::i64, Expand); 308 setOperationAction(ISD::UREM, MVT::i32, Expand); 309 setOperationAction(ISD::UREM, MVT::i64, Expand); 310 311 // Custom lower Add/Sub/Mul with overflow. 312 setOperationAction(ISD::SADDO, MVT::i32, Custom); 313 setOperationAction(ISD::SADDO, MVT::i64, Custom); 314 setOperationAction(ISD::UADDO, MVT::i32, Custom); 315 setOperationAction(ISD::UADDO, MVT::i64, Custom); 316 setOperationAction(ISD::SSUBO, MVT::i32, Custom); 317 setOperationAction(ISD::SSUBO, MVT::i64, Custom); 318 setOperationAction(ISD::USUBO, MVT::i32, Custom); 319 setOperationAction(ISD::USUBO, MVT::i64, Custom); 320 setOperationAction(ISD::SMULO, MVT::i32, Custom); 321 setOperationAction(ISD::SMULO, MVT::i64, Custom); 322 setOperationAction(ISD::UMULO, MVT::i32, Custom); 323 setOperationAction(ISD::UMULO, MVT::i64, Custom); 324 325 setOperationAction(ISD::FSIN, MVT::f32, Expand); 326 setOperationAction(ISD::FSIN, MVT::f64, Expand); 327 setOperationAction(ISD::FCOS, MVT::f32, Expand); 328 setOperationAction(ISD::FCOS, MVT::f64, Expand); 329 setOperationAction(ISD::FPOW, MVT::f32, Expand); 330 setOperationAction(ISD::FPOW, MVT::f64, Expand); 331 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom); 332 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom); 333 if (Subtarget->hasFullFP16()) 334 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom); 335 else 336 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote); 337 338 setOperationAction(ISD::FREM, MVT::f16, Promote); 339 setOperationAction(ISD::FREM, MVT::v4f16, Expand); 340 setOperationAction(ISD::FREM, MVT::v8f16, Expand); 341 setOperationAction(ISD::FPOW, MVT::f16, Promote); 342 setOperationAction(ISD::FPOW, MVT::v4f16, Expand); 343 setOperationAction(ISD::FPOW, MVT::v8f16, Expand); 344 setOperationAction(ISD::FPOWI, MVT::f16, Promote); 345 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand); 346 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand); 347 setOperationAction(ISD::FCOS, MVT::f16, Promote); 348 setOperationAction(ISD::FCOS, MVT::v4f16, Expand); 349 setOperationAction(ISD::FCOS, MVT::v8f16, Expand); 350 setOperationAction(ISD::FSIN, MVT::f16, Promote); 351 setOperationAction(ISD::FSIN, MVT::v4f16, Expand); 352 setOperationAction(ISD::FSIN, MVT::v8f16, Expand); 353 setOperationAction(ISD::FSINCOS, MVT::f16, Promote); 354 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand); 355 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand); 356 setOperationAction(ISD::FEXP, MVT::f16, Promote); 357 setOperationAction(ISD::FEXP, MVT::v4f16, Expand); 358 setOperationAction(ISD::FEXP, MVT::v8f16, Expand); 359 setOperationAction(ISD::FEXP2, MVT::f16, Promote); 360 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand); 361 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand); 362 setOperationAction(ISD::FLOG, MVT::f16, Promote); 363 setOperationAction(ISD::FLOG, MVT::v4f16, Expand); 364 setOperationAction(ISD::FLOG, MVT::v8f16, Expand); 365 setOperationAction(ISD::FLOG2, MVT::f16, Promote); 366 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand); 367 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand); 368 setOperationAction(ISD::FLOG10, MVT::f16, Promote); 369 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand); 370 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand); 371 372 if (!Subtarget->hasFullFP16()) { 373 setOperationAction(ISD::SELECT, MVT::f16, Promote); 374 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote); 375 setOperationAction(ISD::SETCC, MVT::f16, Promote); 376 setOperationAction(ISD::BR_CC, MVT::f16, Promote); 377 setOperationAction(ISD::FADD, MVT::f16, Promote); 378 setOperationAction(ISD::FSUB, MVT::f16, Promote); 379 setOperationAction(ISD::FMUL, MVT::f16, Promote); 380 setOperationAction(ISD::FDIV, MVT::f16, Promote); 381 setOperationAction(ISD::FMA, MVT::f16, Promote); 382 setOperationAction(ISD::FNEG, MVT::f16, Promote); 383 setOperationAction(ISD::FABS, MVT::f16, Promote); 384 setOperationAction(ISD::FCEIL, MVT::f16, Promote); 385 setOperationAction(ISD::FSQRT, MVT::f16, Promote); 386 setOperationAction(ISD::FFLOOR, MVT::f16, Promote); 387 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote); 388 setOperationAction(ISD::FRINT, MVT::f16, Promote); 389 setOperationAction(ISD::FROUND, MVT::f16, Promote); 390 setOperationAction(ISD::FTRUNC, MVT::f16, Promote); 391 setOperationAction(ISD::FMINNUM, MVT::f16, Promote); 392 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote); 393 setOperationAction(ISD::FMINIMUM, MVT::f16, Promote); 394 setOperationAction(ISD::FMAXIMUM, MVT::f16, Promote); 395 396 // promote v4f16 to v4f32 when that is known to be safe. 397 setOperationAction(ISD::FADD, MVT::v4f16, Promote); 398 setOperationAction(ISD::FSUB, MVT::v4f16, Promote); 399 setOperationAction(ISD::FMUL, MVT::v4f16, Promote); 400 setOperationAction(ISD::FDIV, MVT::v4f16, Promote); 401 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote); 402 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote); 403 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32); 404 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32); 405 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32); 406 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32); 407 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32); 408 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32); 409 410 setOperationAction(ISD::FABS, MVT::v4f16, Expand); 411 setOperationAction(ISD::FNEG, MVT::v4f16, Expand); 412 setOperationAction(ISD::FROUND, MVT::v4f16, Expand); 413 setOperationAction(ISD::FMA, MVT::v4f16, Expand); 414 setOperationAction(ISD::SETCC, MVT::v4f16, Expand); 415 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand); 416 setOperationAction(ISD::SELECT, MVT::v4f16, Expand); 417 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand); 418 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand); 419 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand); 420 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand); 421 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand); 422 setOperationAction(ISD::FRINT, MVT::v4f16, Expand); 423 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand); 424 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand); 425 426 setOperationAction(ISD::FABS, MVT::v8f16, Expand); 427 setOperationAction(ISD::FADD, MVT::v8f16, Expand); 428 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand); 429 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand); 430 setOperationAction(ISD::FDIV, MVT::v8f16, Expand); 431 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand); 432 setOperationAction(ISD::FMA, MVT::v8f16, Expand); 433 setOperationAction(ISD::FMUL, MVT::v8f16, Expand); 434 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand); 435 setOperationAction(ISD::FNEG, MVT::v8f16, Expand); 436 setOperationAction(ISD::FROUND, MVT::v8f16, Expand); 437 setOperationAction(ISD::FRINT, MVT::v8f16, Expand); 438 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand); 439 setOperationAction(ISD::FSUB, MVT::v8f16, Expand); 440 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand); 441 setOperationAction(ISD::SETCC, MVT::v8f16, Expand); 442 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand); 443 setOperationAction(ISD::SELECT, MVT::v8f16, Expand); 444 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand); 445 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand); 446 } 447 448 // AArch64 has implementations of a lot of rounding-like FP operations. 449 for (MVT Ty : {MVT::f32, MVT::f64}) { 450 setOperationAction(ISD::FFLOOR, Ty, Legal); 451 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 452 setOperationAction(ISD::FCEIL, Ty, Legal); 453 setOperationAction(ISD::FRINT, Ty, Legal); 454 setOperationAction(ISD::FTRUNC, Ty, Legal); 455 setOperationAction(ISD::FROUND, Ty, Legal); 456 setOperationAction(ISD::FMINNUM, Ty, Legal); 457 setOperationAction(ISD::FMAXNUM, Ty, Legal); 458 setOperationAction(ISD::FMINIMUM, Ty, Legal); 459 setOperationAction(ISD::FMAXIMUM, Ty, Legal); 460 setOperationAction(ISD::LROUND, Ty, Legal); 461 setOperationAction(ISD::LLROUND, Ty, Legal); 462 setOperationAction(ISD::LRINT, Ty, Legal); 463 setOperationAction(ISD::LLRINT, Ty, Legal); 464 } 465 466 if (Subtarget->hasFullFP16()) { 467 setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal); 468 setOperationAction(ISD::FFLOOR, MVT::f16, Legal); 469 setOperationAction(ISD::FCEIL, MVT::f16, Legal); 470 setOperationAction(ISD::FRINT, MVT::f16, Legal); 471 setOperationAction(ISD::FTRUNC, MVT::f16, Legal); 472 setOperationAction(ISD::FROUND, MVT::f16, Legal); 473 setOperationAction(ISD::FMINNUM, MVT::f16, Legal); 474 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal); 475 setOperationAction(ISD::FMINIMUM, MVT::f16, Legal); 476 setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal); 477 } 478 479 setOperationAction(ISD::PREFETCH, MVT::Other, Custom); 480 481 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom); 482 483 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom); 484 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom); 485 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom); 486 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom); 487 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom); 488 489 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0. 490 // This requires the Performance Monitors extension. 491 if (Subtarget->hasPerfMon()) 492 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal); 493 494 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr && 495 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) { 496 // Issue __sincos_stret if available. 497 setOperationAction(ISD::FSINCOS, MVT::f64, Custom); 498 setOperationAction(ISD::FSINCOS, MVT::f32, Custom); 499 } else { 500 setOperationAction(ISD::FSINCOS, MVT::f64, Expand); 501 setOperationAction(ISD::FSINCOS, MVT::f32, Expand); 502 } 503 504 // Make floating-point constants legal for the large code model, so they don't 505 // become loads from the constant pool. 506 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) { 507 setOperationAction(ISD::ConstantFP, MVT::f32, Legal); 508 setOperationAction(ISD::ConstantFP, MVT::f64, Legal); 509 } 510 511 // AArch64 does not have floating-point extending loads, i1 sign-extending 512 // load, floating-point truncating stores, or v2i32->v2i16 truncating store. 513 for (MVT VT : MVT::fp_valuetypes()) { 514 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand); 515 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand); 516 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand); 517 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand); 518 } 519 for (MVT VT : MVT::integer_valuetypes()) 520 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand); 521 522 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 523 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 524 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 525 setTruncStoreAction(MVT::f128, MVT::f80, Expand); 526 setTruncStoreAction(MVT::f128, MVT::f64, Expand); 527 setTruncStoreAction(MVT::f128, MVT::f32, Expand); 528 setTruncStoreAction(MVT::f128, MVT::f16, Expand); 529 530 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 531 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 532 533 // Indexed loads and stores are supported. 534 for (unsigned im = (unsigned)ISD::PRE_INC; 535 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 536 setIndexedLoadAction(im, MVT::i8, Legal); 537 setIndexedLoadAction(im, MVT::i16, Legal); 538 setIndexedLoadAction(im, MVT::i32, Legal); 539 setIndexedLoadAction(im, MVT::i64, Legal); 540 setIndexedLoadAction(im, MVT::f64, Legal); 541 setIndexedLoadAction(im, MVT::f32, Legal); 542 setIndexedLoadAction(im, MVT::f16, Legal); 543 setIndexedStoreAction(im, MVT::i8, Legal); 544 setIndexedStoreAction(im, MVT::i16, Legal); 545 setIndexedStoreAction(im, MVT::i32, Legal); 546 setIndexedStoreAction(im, MVT::i64, Legal); 547 setIndexedStoreAction(im, MVT::f64, Legal); 548 setIndexedStoreAction(im, MVT::f32, Legal); 549 setIndexedStoreAction(im, MVT::f16, Legal); 550 } 551 552 // Trap. 553 setOperationAction(ISD::TRAP, MVT::Other, Legal); 554 if (Subtarget->isTargetWindows()) 555 setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal); 556 557 // We combine OR nodes for bitfield operations. 558 setTargetDAGCombine(ISD::OR); 559 // Try to create BICs for vector ANDs. 560 setTargetDAGCombine(ISD::AND); 561 562 // Vector add and sub nodes may conceal a high-half opportunity. 563 // Also, try to fold ADD into CSINC/CSINV.. 564 setTargetDAGCombine(ISD::ADD); 565 setTargetDAGCombine(ISD::SUB); 566 setTargetDAGCombine(ISD::SRL); 567 setTargetDAGCombine(ISD::XOR); 568 setTargetDAGCombine(ISD::SINT_TO_FP); 569 setTargetDAGCombine(ISD::UINT_TO_FP); 570 571 setTargetDAGCombine(ISD::FP_TO_SINT); 572 setTargetDAGCombine(ISD::FP_TO_UINT); 573 setTargetDAGCombine(ISD::FDIV); 574 575 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN); 576 577 setTargetDAGCombine(ISD::ANY_EXTEND); 578 setTargetDAGCombine(ISD::ZERO_EXTEND); 579 setTargetDAGCombine(ISD::SIGN_EXTEND); 580 setTargetDAGCombine(ISD::BITCAST); 581 setTargetDAGCombine(ISD::CONCAT_VECTORS); 582 setTargetDAGCombine(ISD::STORE); 583 if (Subtarget->supportsAddressTopByteIgnored()) 584 setTargetDAGCombine(ISD::LOAD); 585 586 setTargetDAGCombine(ISD::MUL); 587 588 setTargetDAGCombine(ISD::SELECT); 589 setTargetDAGCombine(ISD::VSELECT); 590 591 setTargetDAGCombine(ISD::INTRINSIC_VOID); 592 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN); 593 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT); 594 595 setTargetDAGCombine(ISD::GlobalAddress); 596 597 // In case of strict alignment, avoid an excessive number of byte wide stores. 598 MaxStoresPerMemsetOptSize = 8; 599 MaxStoresPerMemset = Subtarget->requiresStrictAlign() 600 ? MaxStoresPerMemsetOptSize : 32; 601 602 MaxGluedStoresPerMemcpy = 4; 603 MaxStoresPerMemcpyOptSize = 4; 604 MaxStoresPerMemcpy = Subtarget->requiresStrictAlign() 605 ? MaxStoresPerMemcpyOptSize : 16; 606 607 MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4; 608 609 setStackPointerRegisterToSaveRestore(AArch64::SP); 610 611 setSchedulingPreference(Sched::Hybrid); 612 613 EnableExtLdPromotion = true; 614 615 // Set required alignment. 616 setMinFunctionAlignment(2); 617 // Set preferred alignments. 618 setPrefFunctionAlignment(STI.getPrefFunctionAlignment()); 619 setPrefLoopAlignment(STI.getPrefLoopAlignment()); 620 621 // Only change the limit for entries in a jump table if specified by 622 // the sub target, but not at the command line. 623 unsigned MaxJT = STI.getMaximumJumpTableSize(); 624 if (MaxJT && getMaximumJumpTableSize() == UINT_MAX) 625 setMaximumJumpTableSize(MaxJT); 626 627 setHasExtractBitsInsn(true); 628 629 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 630 631 if (Subtarget->hasNEON()) { 632 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to 633 // silliness like this: 634 setOperationAction(ISD::FABS, MVT::v1f64, Expand); 635 setOperationAction(ISD::FADD, MVT::v1f64, Expand); 636 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand); 637 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand); 638 setOperationAction(ISD::FCOS, MVT::v1f64, Expand); 639 setOperationAction(ISD::FDIV, MVT::v1f64, Expand); 640 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand); 641 setOperationAction(ISD::FMA, MVT::v1f64, Expand); 642 setOperationAction(ISD::FMUL, MVT::v1f64, Expand); 643 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand); 644 setOperationAction(ISD::FNEG, MVT::v1f64, Expand); 645 setOperationAction(ISD::FPOW, MVT::v1f64, Expand); 646 setOperationAction(ISD::FREM, MVT::v1f64, Expand); 647 setOperationAction(ISD::FROUND, MVT::v1f64, Expand); 648 setOperationAction(ISD::FRINT, MVT::v1f64, Expand); 649 setOperationAction(ISD::FSIN, MVT::v1f64, Expand); 650 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand); 651 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand); 652 setOperationAction(ISD::FSUB, MVT::v1f64, Expand); 653 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand); 654 setOperationAction(ISD::SETCC, MVT::v1f64, Expand); 655 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand); 656 setOperationAction(ISD::SELECT, MVT::v1f64, Expand); 657 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand); 658 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand); 659 660 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand); 661 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand); 662 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand); 663 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand); 664 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand); 665 666 setOperationAction(ISD::MUL, MVT::v1i64, Expand); 667 668 // AArch64 doesn't have a direct vector ->f32 conversion instructions for 669 // elements smaller than i32, so promote the input to i32 first. 670 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32); 671 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32); 672 // i8 vector elements also need promotion to i32 for v8i8 673 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32); 674 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32); 675 // Similarly, there is no direct i32 -> f64 vector conversion instruction. 676 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom); 677 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom); 678 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom); 679 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom); 680 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the 681 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16 682 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom); 683 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom); 684 685 if (Subtarget->hasFullFP16()) { 686 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom); 687 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom); 688 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom); 689 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom); 690 } else { 691 // when AArch64 doesn't have fullfp16 support, promote the input 692 // to i32 first. 693 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32); 694 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32); 695 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32); 696 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32); 697 } 698 699 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand); 700 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand); 701 702 // AArch64 doesn't have MUL.2d: 703 setOperationAction(ISD::MUL, MVT::v2i64, Expand); 704 // Custom handling for some quad-vector types to detect MULL. 705 setOperationAction(ISD::MUL, MVT::v8i16, Custom); 706 setOperationAction(ISD::MUL, MVT::v4i32, Custom); 707 setOperationAction(ISD::MUL, MVT::v2i64, Custom); 708 709 // Vector reductions 710 for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32, 711 MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) { 712 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom); 713 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom); 714 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom); 715 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom); 716 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom); 717 } 718 for (MVT VT : { MVT::v4f16, MVT::v2f32, 719 MVT::v8f16, MVT::v4f32, MVT::v2f64 }) { 720 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 721 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 722 } 723 724 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal); 725 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand); 726 // Likewise, narrowing and extending vector loads/stores aren't handled 727 // directly. 728 for (MVT VT : MVT::vector_valuetypes()) { 729 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand); 730 731 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) { 732 setOperationAction(ISD::MULHS, VT, Legal); 733 setOperationAction(ISD::MULHU, VT, Legal); 734 } else { 735 setOperationAction(ISD::MULHS, VT, Expand); 736 setOperationAction(ISD::MULHU, VT, Expand); 737 } 738 setOperationAction(ISD::SMUL_LOHI, VT, Expand); 739 setOperationAction(ISD::UMUL_LOHI, VT, Expand); 740 741 setOperationAction(ISD::BSWAP, VT, Expand); 742 setOperationAction(ISD::CTTZ, VT, Expand); 743 744 for (MVT InnerVT : MVT::vector_valuetypes()) { 745 setTruncStoreAction(VT, InnerVT, Expand); 746 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand); 747 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand); 748 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand); 749 } 750 } 751 752 // AArch64 has implementations of a lot of rounding-like FP operations. 753 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) { 754 setOperationAction(ISD::FFLOOR, Ty, Legal); 755 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 756 setOperationAction(ISD::FCEIL, Ty, Legal); 757 setOperationAction(ISD::FRINT, Ty, Legal); 758 setOperationAction(ISD::FTRUNC, Ty, Legal); 759 setOperationAction(ISD::FROUND, Ty, Legal); 760 } 761 762 if (Subtarget->hasFullFP16()) { 763 for (MVT Ty : {MVT::v4f16, MVT::v8f16}) { 764 setOperationAction(ISD::FFLOOR, Ty, Legal); 765 setOperationAction(ISD::FNEARBYINT, Ty, Legal); 766 setOperationAction(ISD::FCEIL, Ty, Legal); 767 setOperationAction(ISD::FRINT, Ty, Legal); 768 setOperationAction(ISD::FTRUNC, Ty, Legal); 769 setOperationAction(ISD::FROUND, Ty, Legal); 770 } 771 } 772 773 setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom); 774 } 775 776 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive(); 777 } 778 779 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) { 780 assert(VT.isVector() && "VT should be a vector type"); 781 782 if (VT.isFloatingPoint()) { 783 MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT(); 784 setOperationPromotedToType(ISD::LOAD, VT, PromoteTo); 785 setOperationPromotedToType(ISD::STORE, VT, PromoteTo); 786 } 787 788 // Mark vector float intrinsics as expand. 789 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) { 790 setOperationAction(ISD::FSIN, VT, Expand); 791 setOperationAction(ISD::FCOS, VT, Expand); 792 setOperationAction(ISD::FPOW, VT, Expand); 793 setOperationAction(ISD::FLOG, VT, Expand); 794 setOperationAction(ISD::FLOG2, VT, Expand); 795 setOperationAction(ISD::FLOG10, VT, Expand); 796 setOperationAction(ISD::FEXP, VT, Expand); 797 setOperationAction(ISD::FEXP2, VT, Expand); 798 799 // But we do support custom-lowering for FCOPYSIGN. 800 setOperationAction(ISD::FCOPYSIGN, VT, Custom); 801 } 802 803 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom); 804 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 805 setOperationAction(ISD::BUILD_VECTOR, VT, Custom); 806 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 807 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom); 808 setOperationAction(ISD::SRA, VT, Custom); 809 setOperationAction(ISD::SRL, VT, Custom); 810 setOperationAction(ISD::SHL, VT, Custom); 811 setOperationAction(ISD::OR, VT, Custom); 812 setOperationAction(ISD::SETCC, VT, Custom); 813 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal); 814 815 setOperationAction(ISD::SELECT, VT, Expand); 816 setOperationAction(ISD::SELECT_CC, VT, Expand); 817 setOperationAction(ISD::VSELECT, VT, Expand); 818 for (MVT InnerVT : MVT::all_valuetypes()) 819 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand); 820 821 // CNT supports only B element sizes, then use UADDLP to widen. 822 if (VT != MVT::v8i8 && VT != MVT::v16i8) 823 setOperationAction(ISD::CTPOP, VT, Custom); 824 825 setOperationAction(ISD::UDIV, VT, Expand); 826 setOperationAction(ISD::SDIV, VT, Expand); 827 setOperationAction(ISD::UREM, VT, Expand); 828 setOperationAction(ISD::SREM, VT, Expand); 829 setOperationAction(ISD::FREM, VT, Expand); 830 831 setOperationAction(ISD::FP_TO_SINT, VT, Custom); 832 setOperationAction(ISD::FP_TO_UINT, VT, Custom); 833 834 if (!VT.isFloatingPoint()) 835 setOperationAction(ISD::ABS, VT, Legal); 836 837 // [SU][MIN|MAX] are available for all NEON types apart from i64. 838 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64) 839 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}) 840 setOperationAction(Opcode, VT, Legal); 841 842 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types. 843 if (VT.isFloatingPoint() && 844 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16())) 845 for (unsigned Opcode : 846 {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM}) 847 setOperationAction(Opcode, VT, Legal); 848 849 if (Subtarget->isLittleEndian()) { 850 for (unsigned im = (unsigned)ISD::PRE_INC; 851 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) { 852 setIndexedLoadAction(im, VT, Legal); 853 setIndexedStoreAction(im, VT, Legal); 854 } 855 } 856 } 857 858 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) { 859 addRegisterClass(VT, &AArch64::FPR64RegClass); 860 addTypeForNEON(VT, MVT::v2i32); 861 } 862 863 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) { 864 addRegisterClass(VT, &AArch64::FPR128RegClass); 865 addTypeForNEON(VT, MVT::v4i32); 866 } 867 868 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &, 869 EVT VT) const { 870 if (!VT.isVector()) 871 return MVT::i32; 872 return VT.changeVectorElementTypeToInteger(); 873 } 874 875 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm, 876 const APInt &Demanded, 877 TargetLowering::TargetLoweringOpt &TLO, 878 unsigned NewOpc) { 879 uint64_t OldImm = Imm, NewImm, Enc; 880 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask; 881 882 // Return if the immediate is already all zeros, all ones, a bimm32 or a 883 // bimm64. 884 if (Imm == 0 || Imm == Mask || 885 AArch64_AM::isLogicalImmediate(Imm & Mask, Size)) 886 return false; 887 888 unsigned EltSize = Size; 889 uint64_t DemandedBits = Demanded.getZExtValue(); 890 891 // Clear bits that are not demanded. 892 Imm &= DemandedBits; 893 894 while (true) { 895 // The goal here is to set the non-demanded bits in a way that minimizes 896 // the number of switching between 0 and 1. In order to achieve this goal, 897 // we set the non-demanded bits to the value of the preceding demanded bits. 898 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a 899 // non-demanded bit), we copy bit0 (1) to the least significant 'x', 900 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'. 901 // The final result is 0b11000011. 902 uint64_t NonDemandedBits = ~DemandedBits; 903 uint64_t InvertedImm = ~Imm & DemandedBits; 904 uint64_t RotatedImm = 905 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) & 906 NonDemandedBits; 907 uint64_t Sum = RotatedImm + NonDemandedBits; 908 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1)); 909 uint64_t Ones = (Sum + Carry) & NonDemandedBits; 910 NewImm = (Imm | Ones) & Mask; 911 912 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate 913 // or all-ones or all-zeros, in which case we can stop searching. Otherwise, 914 // we halve the element size and continue the search. 915 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask))) 916 break; 917 918 // We cannot shrink the element size any further if it is 2-bits. 919 if (EltSize == 2) 920 return false; 921 922 EltSize /= 2; 923 Mask >>= EltSize; 924 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize; 925 926 // Return if there is mismatch in any of the demanded bits of Imm and Hi. 927 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0) 928 return false; 929 930 // Merge the upper and lower halves of Imm and DemandedBits. 931 Imm |= Hi; 932 DemandedBits |= DemandedBitsHi; 933 } 934 935 ++NumOptimizedImms; 936 937 // Replicate the element across the register width. 938 while (EltSize < Size) { 939 NewImm |= NewImm << EltSize; 940 EltSize *= 2; 941 } 942 943 (void)OldImm; 944 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 && 945 "demanded bits should never be altered"); 946 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm"); 947 948 // Create the new constant immediate node. 949 EVT VT = Op.getValueType(); 950 SDLoc DL(Op); 951 SDValue New; 952 953 // If the new constant immediate is all-zeros or all-ones, let the target 954 // independent DAG combine optimize this node. 955 if (NewImm == 0 || NewImm == OrigMask) { 956 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0), 957 TLO.DAG.getConstant(NewImm, DL, VT)); 958 // Otherwise, create a machine node so that target independent DAG combine 959 // doesn't undo this optimization. 960 } else { 961 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size); 962 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT); 963 New = SDValue( 964 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0); 965 } 966 967 return TLO.CombineTo(Op, New); 968 } 969 970 bool AArch64TargetLowering::targetShrinkDemandedConstant( 971 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const { 972 // Delay this optimization to as late as possible. 973 if (!TLO.LegalOps) 974 return false; 975 976 if (!EnableOptimizeLogicalImm) 977 return false; 978 979 EVT VT = Op.getValueType(); 980 if (VT.isVector()) 981 return false; 982 983 unsigned Size = VT.getSizeInBits(); 984 assert((Size == 32 || Size == 64) && 985 "i32 or i64 is expected after legalization."); 986 987 // Exit early if we demand all bits. 988 if (Demanded.countPopulation() == Size) 989 return false; 990 991 unsigned NewOpc; 992 switch (Op.getOpcode()) { 993 default: 994 return false; 995 case ISD::AND: 996 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri; 997 break; 998 case ISD::OR: 999 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri; 1000 break; 1001 case ISD::XOR: 1002 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri; 1003 break; 1004 } 1005 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 1006 if (!C) 1007 return false; 1008 uint64_t Imm = C->getZExtValue(); 1009 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc); 1010 } 1011 1012 /// computeKnownBitsForTargetNode - Determine which of the bits specified in 1013 /// Mask are known to be either zero or one and return them Known. 1014 void AArch64TargetLowering::computeKnownBitsForTargetNode( 1015 const SDValue Op, KnownBits &Known, 1016 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const { 1017 switch (Op.getOpcode()) { 1018 default: 1019 break; 1020 case AArch64ISD::CSEL: { 1021 KnownBits Known2; 1022 Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1); 1023 Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1); 1024 Known.Zero &= Known2.Zero; 1025 Known.One &= Known2.One; 1026 break; 1027 } 1028 case ISD::INTRINSIC_W_CHAIN: { 1029 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1)); 1030 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue()); 1031 switch (IntID) { 1032 default: return; 1033 case Intrinsic::aarch64_ldaxr: 1034 case Intrinsic::aarch64_ldxr: { 1035 unsigned BitWidth = Known.getBitWidth(); 1036 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT(); 1037 unsigned MemBits = VT.getScalarSizeInBits(); 1038 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits); 1039 return; 1040 } 1041 } 1042 break; 1043 } 1044 case ISD::INTRINSIC_WO_CHAIN: 1045 case ISD::INTRINSIC_VOID: { 1046 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 1047 switch (IntNo) { 1048 default: 1049 break; 1050 case Intrinsic::aarch64_neon_umaxv: 1051 case Intrinsic::aarch64_neon_uminv: { 1052 // Figure out the datatype of the vector operand. The UMINV instruction 1053 // will zero extend the result, so we can mark as known zero all the 1054 // bits larger than the element datatype. 32-bit or larget doesn't need 1055 // this as those are legal types and will be handled by isel directly. 1056 MVT VT = Op.getOperand(1).getValueType().getSimpleVT(); 1057 unsigned BitWidth = Known.getBitWidth(); 1058 if (VT == MVT::v8i8 || VT == MVT::v16i8) { 1059 assert(BitWidth >= 8 && "Unexpected width!"); 1060 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8); 1061 Known.Zero |= Mask; 1062 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) { 1063 assert(BitWidth >= 16 && "Unexpected width!"); 1064 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16); 1065 Known.Zero |= Mask; 1066 } 1067 break; 1068 } break; 1069 } 1070 } 1071 } 1072 } 1073 1074 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL, 1075 EVT) const { 1076 return MVT::i64; 1077 } 1078 1079 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses( 1080 EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags, 1081 bool *Fast) const { 1082 if (Subtarget->requiresStrictAlign()) 1083 return false; 1084 1085 if (Fast) { 1086 // Some CPUs are fine with unaligned stores except for 128-bit ones. 1087 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 || 1088 // See comments in performSTORECombine() for more details about 1089 // these conditions. 1090 1091 // Code that uses clang vector extensions can mark that it 1092 // wants unaligned accesses to be treated as fast by 1093 // underspecifying alignment to be 1 or 2. 1094 Align <= 2 || 1095 1096 // Disregard v2i64. Memcpy lowering produces those and splitting 1097 // them regresses performance on micro-benchmarks and olden/bh. 1098 VT == MVT::v2i64; 1099 } 1100 return true; 1101 } 1102 1103 FastISel * 1104 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo, 1105 const TargetLibraryInfo *libInfo) const { 1106 return AArch64::createFastISel(funcInfo, libInfo); 1107 } 1108 1109 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const { 1110 switch ((AArch64ISD::NodeType)Opcode) { 1111 case AArch64ISD::FIRST_NUMBER: break; 1112 case AArch64ISD::CALL: return "AArch64ISD::CALL"; 1113 case AArch64ISD::ADRP: return "AArch64ISD::ADRP"; 1114 case AArch64ISD::ADR: return "AArch64ISD::ADR"; 1115 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow"; 1116 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot"; 1117 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG"; 1118 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND"; 1119 case AArch64ISD::CSEL: return "AArch64ISD::CSEL"; 1120 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL"; 1121 case AArch64ISD::CSINV: return "AArch64ISD::CSINV"; 1122 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG"; 1123 case AArch64ISD::CSINC: return "AArch64ISD::CSINC"; 1124 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER"; 1125 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ"; 1126 case AArch64ISD::ADC: return "AArch64ISD::ADC"; 1127 case AArch64ISD::SBC: return "AArch64ISD::SBC"; 1128 case AArch64ISD::ADDS: return "AArch64ISD::ADDS"; 1129 case AArch64ISD::SUBS: return "AArch64ISD::SUBS"; 1130 case AArch64ISD::ADCS: return "AArch64ISD::ADCS"; 1131 case AArch64ISD::SBCS: return "AArch64ISD::SBCS"; 1132 case AArch64ISD::ANDS: return "AArch64ISD::ANDS"; 1133 case AArch64ISD::CCMP: return "AArch64ISD::CCMP"; 1134 case AArch64ISD::CCMN: return "AArch64ISD::CCMN"; 1135 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP"; 1136 case AArch64ISD::FCMP: return "AArch64ISD::FCMP"; 1137 case AArch64ISD::DUP: return "AArch64ISD::DUP"; 1138 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8"; 1139 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16"; 1140 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32"; 1141 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64"; 1142 case AArch64ISD::MOVI: return "AArch64ISD::MOVI"; 1143 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift"; 1144 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit"; 1145 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl"; 1146 case AArch64ISD::FMOV: return "AArch64ISD::FMOV"; 1147 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift"; 1148 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl"; 1149 case AArch64ISD::BICi: return "AArch64ISD::BICi"; 1150 case AArch64ISD::ORRi: return "AArch64ISD::ORRi"; 1151 case AArch64ISD::BSL: return "AArch64ISD::BSL"; 1152 case AArch64ISD::NEG: return "AArch64ISD::NEG"; 1153 case AArch64ISD::EXTR: return "AArch64ISD::EXTR"; 1154 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1"; 1155 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2"; 1156 case AArch64ISD::UZP1: return "AArch64ISD::UZP1"; 1157 case AArch64ISD::UZP2: return "AArch64ISD::UZP2"; 1158 case AArch64ISD::TRN1: return "AArch64ISD::TRN1"; 1159 case AArch64ISD::TRN2: return "AArch64ISD::TRN2"; 1160 case AArch64ISD::REV16: return "AArch64ISD::REV16"; 1161 case AArch64ISD::REV32: return "AArch64ISD::REV32"; 1162 case AArch64ISD::REV64: return "AArch64ISD::REV64"; 1163 case AArch64ISD::EXT: return "AArch64ISD::EXT"; 1164 case AArch64ISD::VSHL: return "AArch64ISD::VSHL"; 1165 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR"; 1166 case AArch64ISD::VASHR: return "AArch64ISD::VASHR"; 1167 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ"; 1168 case AArch64ISD::CMGE: return "AArch64ISD::CMGE"; 1169 case AArch64ISD::CMGT: return "AArch64ISD::CMGT"; 1170 case AArch64ISD::CMHI: return "AArch64ISD::CMHI"; 1171 case AArch64ISD::CMHS: return "AArch64ISD::CMHS"; 1172 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ"; 1173 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE"; 1174 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT"; 1175 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz"; 1176 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz"; 1177 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz"; 1178 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz"; 1179 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz"; 1180 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz"; 1181 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz"; 1182 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz"; 1183 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz"; 1184 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz"; 1185 case AArch64ISD::SADDV: return "AArch64ISD::SADDV"; 1186 case AArch64ISD::UADDV: return "AArch64ISD::UADDV"; 1187 case AArch64ISD::SMINV: return "AArch64ISD::SMINV"; 1188 case AArch64ISD::UMINV: return "AArch64ISD::UMINV"; 1189 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV"; 1190 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV"; 1191 case AArch64ISD::NOT: return "AArch64ISD::NOT"; 1192 case AArch64ISD::BIT: return "AArch64ISD::BIT"; 1193 case AArch64ISD::CBZ: return "AArch64ISD::CBZ"; 1194 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ"; 1195 case AArch64ISD::TBZ: return "AArch64ISD::TBZ"; 1196 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ"; 1197 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN"; 1198 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH"; 1199 case AArch64ISD::SITOF: return "AArch64ISD::SITOF"; 1200 case AArch64ISD::UITOF: return "AArch64ISD::UITOF"; 1201 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST"; 1202 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I"; 1203 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I"; 1204 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I"; 1205 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I"; 1206 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I"; 1207 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge"; 1208 case AArch64ISD::LD2post: return "AArch64ISD::LD2post"; 1209 case AArch64ISD::LD3post: return "AArch64ISD::LD3post"; 1210 case AArch64ISD::LD4post: return "AArch64ISD::LD4post"; 1211 case AArch64ISD::ST2post: return "AArch64ISD::ST2post"; 1212 case AArch64ISD::ST3post: return "AArch64ISD::ST3post"; 1213 case AArch64ISD::ST4post: return "AArch64ISD::ST4post"; 1214 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post"; 1215 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post"; 1216 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post"; 1217 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post"; 1218 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post"; 1219 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post"; 1220 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost"; 1221 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost"; 1222 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost"; 1223 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost"; 1224 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost"; 1225 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost"; 1226 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost"; 1227 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost"; 1228 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost"; 1229 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost"; 1230 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost"; 1231 case AArch64ISD::SMULL: return "AArch64ISD::SMULL"; 1232 case AArch64ISD::UMULL: return "AArch64ISD::UMULL"; 1233 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE"; 1234 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS"; 1235 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE"; 1236 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS"; 1237 } 1238 return nullptr; 1239 } 1240 1241 MachineBasicBlock * 1242 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI, 1243 MachineBasicBlock *MBB) const { 1244 // We materialise the F128CSEL pseudo-instruction as some control flow and a 1245 // phi node: 1246 1247 // OrigBB: 1248 // [... previous instrs leading to comparison ...] 1249 // b.ne TrueBB 1250 // b EndBB 1251 // TrueBB: 1252 // ; Fallthrough 1253 // EndBB: 1254 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB] 1255 1256 MachineFunction *MF = MBB->getParent(); 1257 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 1258 const BasicBlock *LLVM_BB = MBB->getBasicBlock(); 1259 DebugLoc DL = MI.getDebugLoc(); 1260 MachineFunction::iterator It = ++MBB->getIterator(); 1261 1262 unsigned DestReg = MI.getOperand(0).getReg(); 1263 unsigned IfTrueReg = MI.getOperand(1).getReg(); 1264 unsigned IfFalseReg = MI.getOperand(2).getReg(); 1265 unsigned CondCode = MI.getOperand(3).getImm(); 1266 bool NZCVKilled = MI.getOperand(4).isKill(); 1267 1268 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB); 1269 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB); 1270 MF->insert(It, TrueBB); 1271 MF->insert(It, EndBB); 1272 1273 // Transfer rest of current basic-block to EndBB 1274 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)), 1275 MBB->end()); 1276 EndBB->transferSuccessorsAndUpdatePHIs(MBB); 1277 1278 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB); 1279 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB); 1280 MBB->addSuccessor(TrueBB); 1281 MBB->addSuccessor(EndBB); 1282 1283 // TrueBB falls through to the end. 1284 TrueBB->addSuccessor(EndBB); 1285 1286 if (!NZCVKilled) { 1287 TrueBB->addLiveIn(AArch64::NZCV); 1288 EndBB->addLiveIn(AArch64::NZCV); 1289 } 1290 1291 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg) 1292 .addReg(IfTrueReg) 1293 .addMBB(TrueBB) 1294 .addReg(IfFalseReg) 1295 .addMBB(MBB); 1296 1297 MI.eraseFromParent(); 1298 return EndBB; 1299 } 1300 1301 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet( 1302 MachineInstr &MI, MachineBasicBlock *BB) const { 1303 assert(!isAsynchronousEHPersonality(classifyEHPersonality( 1304 BB->getParent()->getFunction().getPersonalityFn())) && 1305 "SEH does not use catchret!"); 1306 return BB; 1307 } 1308 1309 MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchPad( 1310 MachineInstr &MI, MachineBasicBlock *BB) const { 1311 MI.eraseFromParent(); 1312 return BB; 1313 } 1314 1315 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter( 1316 MachineInstr &MI, MachineBasicBlock *BB) const { 1317 switch (MI.getOpcode()) { 1318 default: 1319 #ifndef NDEBUG 1320 MI.dump(); 1321 #endif 1322 llvm_unreachable("Unexpected instruction for custom inserter!"); 1323 1324 case AArch64::F128CSEL: 1325 return EmitF128CSEL(MI, BB); 1326 1327 case TargetOpcode::STACKMAP: 1328 case TargetOpcode::PATCHPOINT: 1329 return emitPatchPoint(MI, BB); 1330 1331 case AArch64::CATCHRET: 1332 return EmitLoweredCatchRet(MI, BB); 1333 case AArch64::CATCHPAD: 1334 return EmitLoweredCatchPad(MI, BB); 1335 } 1336 } 1337 1338 //===----------------------------------------------------------------------===// 1339 // AArch64 Lowering private implementation. 1340 //===----------------------------------------------------------------------===// 1341 1342 //===----------------------------------------------------------------------===// 1343 // Lowering Code 1344 //===----------------------------------------------------------------------===// 1345 1346 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64 1347 /// CC 1348 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) { 1349 switch (CC) { 1350 default: 1351 llvm_unreachable("Unknown condition code!"); 1352 case ISD::SETNE: 1353 return AArch64CC::NE; 1354 case ISD::SETEQ: 1355 return AArch64CC::EQ; 1356 case ISD::SETGT: 1357 return AArch64CC::GT; 1358 case ISD::SETGE: 1359 return AArch64CC::GE; 1360 case ISD::SETLT: 1361 return AArch64CC::LT; 1362 case ISD::SETLE: 1363 return AArch64CC::LE; 1364 case ISD::SETUGT: 1365 return AArch64CC::HI; 1366 case ISD::SETUGE: 1367 return AArch64CC::HS; 1368 case ISD::SETULT: 1369 return AArch64CC::LO; 1370 case ISD::SETULE: 1371 return AArch64CC::LS; 1372 } 1373 } 1374 1375 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC. 1376 static void changeFPCCToAArch64CC(ISD::CondCode CC, 1377 AArch64CC::CondCode &CondCode, 1378 AArch64CC::CondCode &CondCode2) { 1379 CondCode2 = AArch64CC::AL; 1380 switch (CC) { 1381 default: 1382 llvm_unreachable("Unknown FP condition!"); 1383 case ISD::SETEQ: 1384 case ISD::SETOEQ: 1385 CondCode = AArch64CC::EQ; 1386 break; 1387 case ISD::SETGT: 1388 case ISD::SETOGT: 1389 CondCode = AArch64CC::GT; 1390 break; 1391 case ISD::SETGE: 1392 case ISD::SETOGE: 1393 CondCode = AArch64CC::GE; 1394 break; 1395 case ISD::SETOLT: 1396 CondCode = AArch64CC::MI; 1397 break; 1398 case ISD::SETOLE: 1399 CondCode = AArch64CC::LS; 1400 break; 1401 case ISD::SETONE: 1402 CondCode = AArch64CC::MI; 1403 CondCode2 = AArch64CC::GT; 1404 break; 1405 case ISD::SETO: 1406 CondCode = AArch64CC::VC; 1407 break; 1408 case ISD::SETUO: 1409 CondCode = AArch64CC::VS; 1410 break; 1411 case ISD::SETUEQ: 1412 CondCode = AArch64CC::EQ; 1413 CondCode2 = AArch64CC::VS; 1414 break; 1415 case ISD::SETUGT: 1416 CondCode = AArch64CC::HI; 1417 break; 1418 case ISD::SETUGE: 1419 CondCode = AArch64CC::PL; 1420 break; 1421 case ISD::SETLT: 1422 case ISD::SETULT: 1423 CondCode = AArch64CC::LT; 1424 break; 1425 case ISD::SETLE: 1426 case ISD::SETULE: 1427 CondCode = AArch64CC::LE; 1428 break; 1429 case ISD::SETNE: 1430 case ISD::SETUNE: 1431 CondCode = AArch64CC::NE; 1432 break; 1433 } 1434 } 1435 1436 /// Convert a DAG fp condition code to an AArch64 CC. 1437 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that 1438 /// should be AND'ed instead of OR'ed. 1439 static void changeFPCCToANDAArch64CC(ISD::CondCode CC, 1440 AArch64CC::CondCode &CondCode, 1441 AArch64CC::CondCode &CondCode2) { 1442 CondCode2 = AArch64CC::AL; 1443 switch (CC) { 1444 default: 1445 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 1446 assert(CondCode2 == AArch64CC::AL); 1447 break; 1448 case ISD::SETONE: 1449 // (a one b) 1450 // == ((a olt b) || (a ogt b)) 1451 // == ((a ord b) && (a une b)) 1452 CondCode = AArch64CC::VC; 1453 CondCode2 = AArch64CC::NE; 1454 break; 1455 case ISD::SETUEQ: 1456 // (a ueq b) 1457 // == ((a uno b) || (a oeq b)) 1458 // == ((a ule b) && (a uge b)) 1459 CondCode = AArch64CC::PL; 1460 CondCode2 = AArch64CC::LE; 1461 break; 1462 } 1463 } 1464 1465 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 1466 /// CC usable with the vector instructions. Fewer operations are available 1467 /// without a real NZCV register, so we have to use less efficient combinations 1468 /// to get the same effect. 1469 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC, 1470 AArch64CC::CondCode &CondCode, 1471 AArch64CC::CondCode &CondCode2, 1472 bool &Invert) { 1473 Invert = false; 1474 switch (CC) { 1475 default: 1476 // Mostly the scalar mappings work fine. 1477 changeFPCCToAArch64CC(CC, CondCode, CondCode2); 1478 break; 1479 case ISD::SETUO: 1480 Invert = true; 1481 LLVM_FALLTHROUGH; 1482 case ISD::SETO: 1483 CondCode = AArch64CC::MI; 1484 CondCode2 = AArch64CC::GE; 1485 break; 1486 case ISD::SETUEQ: 1487 case ISD::SETULT: 1488 case ISD::SETULE: 1489 case ISD::SETUGT: 1490 case ISD::SETUGE: 1491 // All of the compare-mask comparisons are ordered, but we can switch 1492 // between the two by a double inversion. E.g. ULE == !OGT. 1493 Invert = true; 1494 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2); 1495 break; 1496 } 1497 } 1498 1499 static bool isLegalArithImmed(uint64_t C) { 1500 // Matches AArch64DAGToDAGISel::SelectArithImmed(). 1501 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0); 1502 LLVM_DEBUG(dbgs() << "Is imm " << C 1503 << " legal: " << (IsLegal ? "yes\n" : "no\n")); 1504 return IsLegal; 1505 } 1506 1507 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on 1508 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags 1509 // can be set differently by this operation. It comes down to whether 1510 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then 1511 // everything is fine. If not then the optimization is wrong. Thus general 1512 // comparisons are only valid if op2 != 0. 1513 // 1514 // So, finally, the only LLVM-native comparisons that don't mention C and V 1515 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in 1516 // the absence of information about op2. 1517 static bool isCMN(SDValue Op, ISD::CondCode CC) { 1518 return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) && 1519 (CC == ISD::SETEQ || CC == ISD::SETNE); 1520 } 1521 1522 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC, 1523 const SDLoc &dl, SelectionDAG &DAG) { 1524 EVT VT = LHS.getValueType(); 1525 const bool FullFP16 = 1526 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 1527 1528 if (VT.isFloatingPoint()) { 1529 assert(VT != MVT::f128); 1530 if (VT == MVT::f16 && !FullFP16) { 1531 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 1532 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 1533 VT = MVT::f32; 1534 } 1535 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS); 1536 } 1537 1538 // The CMP instruction is just an alias for SUBS, and representing it as 1539 // SUBS means that it's possible to get CSE with subtract operations. 1540 // A later phase can perform the optimization of setting the destination 1541 // register to WZR/XZR if it ends up being unused. 1542 unsigned Opcode = AArch64ISD::SUBS; 1543 1544 if (isCMN(RHS, CC)) { 1545 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ? 1546 Opcode = AArch64ISD::ADDS; 1547 RHS = RHS.getOperand(1); 1548 } else if (isCMN(LHS, CC)) { 1549 // As we are looking for EQ/NE compares, the operands can be commuted ; can 1550 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ? 1551 Opcode = AArch64ISD::ADDS; 1552 LHS = LHS.getOperand(1); 1553 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) && 1554 !isUnsignedIntSetCC(CC)) { 1555 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST 1556 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one 1557 // of the signed comparisons. 1558 Opcode = AArch64ISD::ANDS; 1559 RHS = LHS.getOperand(1); 1560 LHS = LHS.getOperand(0); 1561 } 1562 1563 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS) 1564 .getValue(1); 1565 } 1566 1567 /// \defgroup AArch64CCMP CMP;CCMP matching 1568 /// 1569 /// These functions deal with the formation of CMP;CCMP;... sequences. 1570 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of 1571 /// a comparison. They set the NZCV flags to a predefined value if their 1572 /// predicate is false. This allows to express arbitrary conjunctions, for 1573 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))" 1574 /// expressed as: 1575 /// cmp A 1576 /// ccmp B, inv(CB), CA 1577 /// check for CB flags 1578 /// 1579 /// This naturally lets us implement chains of AND operations with SETCC 1580 /// operands. And we can even implement some other situations by transforming 1581 /// them: 1582 /// - We can implement (NEG SETCC) i.e. negating a single comparison by 1583 /// negating the flags used in a CCMP/FCCMP operations. 1584 /// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations 1585 /// by negating the flags we test for afterwards. i.e. 1586 /// NEG (CMP CCMP CCCMP ...) can be implemented. 1587 /// - Note that we can only ever negate all previously processed results. 1588 /// What we can not implement by flipping the flags to test is a negation 1589 /// of two sub-trees (because the negation affects all sub-trees emitted so 1590 /// far, so the 2nd sub-tree we emit would also affect the first). 1591 /// With those tools we can implement some OR operations: 1592 /// - (OR (SETCC A) (SETCC B)) can be implemented via: 1593 /// NEG (AND (NEG (SETCC A)) (NEG (SETCC B))) 1594 /// - After transforming OR to NEG/AND combinations we may be able to use NEG 1595 /// elimination rules from earlier to implement the whole thing as a 1596 /// CCMP/FCCMP chain. 1597 /// 1598 /// As complete example: 1599 /// or (or (setCA (cmp A)) (setCB (cmp B))) 1600 /// (and (setCC (cmp C)) (setCD (cmp D)))" 1601 /// can be reassociated to: 1602 /// or (and (setCC (cmp C)) setCD (cmp D)) 1603 // (or (setCA (cmp A)) (setCB (cmp B))) 1604 /// can be transformed to: 1605 /// not (and (not (and (setCC (cmp C)) (setCD (cmp D)))) 1606 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))" 1607 /// which can be implemented as: 1608 /// cmp C 1609 /// ccmp D, inv(CD), CC 1610 /// ccmp A, CA, inv(CD) 1611 /// ccmp B, CB, inv(CA) 1612 /// check for CB flags 1613 /// 1614 /// A counterexample is "or (and A B) (and C D)" which translates to 1615 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we 1616 /// can only implement 1 of the inner (not) operations, but not both! 1617 /// @{ 1618 1619 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate. 1620 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS, 1621 ISD::CondCode CC, SDValue CCOp, 1622 AArch64CC::CondCode Predicate, 1623 AArch64CC::CondCode OutCC, 1624 const SDLoc &DL, SelectionDAG &DAG) { 1625 unsigned Opcode = 0; 1626 const bool FullFP16 = 1627 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 1628 1629 if (LHS.getValueType().isFloatingPoint()) { 1630 assert(LHS.getValueType() != MVT::f128); 1631 if (LHS.getValueType() == MVT::f16 && !FullFP16) { 1632 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS); 1633 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS); 1634 } 1635 Opcode = AArch64ISD::FCCMP; 1636 } else if (RHS.getOpcode() == ISD::SUB) { 1637 SDValue SubOp0 = RHS.getOperand(0); 1638 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) { 1639 // See emitComparison() on why we can only do this for SETEQ and SETNE. 1640 Opcode = AArch64ISD::CCMN; 1641 RHS = RHS.getOperand(1); 1642 } 1643 } 1644 if (Opcode == 0) 1645 Opcode = AArch64ISD::CCMP; 1646 1647 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC); 1648 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC); 1649 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC); 1650 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32); 1651 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp); 1652 } 1653 1654 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be 1655 /// expressed as a conjunction. See \ref AArch64CCMP. 1656 /// \param CanNegate Set to true if we can negate the whole sub-tree just by 1657 /// changing the conditions on the SETCC tests. 1658 /// (this means we can call emitConjunctionRec() with 1659 /// Negate==true on this sub-tree) 1660 /// \param MustBeFirst Set to true if this subtree needs to be negated and we 1661 /// cannot do the negation naturally. We are required to 1662 /// emit the subtree first in this case. 1663 /// \param WillNegate Is true if are called when the result of this 1664 /// subexpression must be negated. This happens when the 1665 /// outer expression is an OR. We can use this fact to know 1666 /// that we have a double negation (or (or ...) ...) that 1667 /// can be implemented for free. 1668 static bool canEmitConjunction(const SDValue Val, bool &CanNegate, 1669 bool &MustBeFirst, bool WillNegate, 1670 unsigned Depth = 0) { 1671 if (!Val.hasOneUse()) 1672 return false; 1673 unsigned Opcode = Val->getOpcode(); 1674 if (Opcode == ISD::SETCC) { 1675 if (Val->getOperand(0).getValueType() == MVT::f128) 1676 return false; 1677 CanNegate = true; 1678 MustBeFirst = false; 1679 return true; 1680 } 1681 // Protect against exponential runtime and stack overflow. 1682 if (Depth > 6) 1683 return false; 1684 if (Opcode == ISD::AND || Opcode == ISD::OR) { 1685 bool IsOR = Opcode == ISD::OR; 1686 SDValue O0 = Val->getOperand(0); 1687 SDValue O1 = Val->getOperand(1); 1688 bool CanNegateL; 1689 bool MustBeFirstL; 1690 if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1)) 1691 return false; 1692 bool CanNegateR; 1693 bool MustBeFirstR; 1694 if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1)) 1695 return false; 1696 1697 if (MustBeFirstL && MustBeFirstR) 1698 return false; 1699 1700 if (IsOR) { 1701 // For an OR expression we need to be able to naturally negate at least 1702 // one side or we cannot do the transformation at all. 1703 if (!CanNegateL && !CanNegateR) 1704 return false; 1705 // If we the result of the OR will be negated and we can naturally negate 1706 // the leafs, then this sub-tree as a whole negates naturally. 1707 CanNegate = WillNegate && CanNegateL && CanNegateR; 1708 // If we cannot naturally negate the whole sub-tree, then this must be 1709 // emitted first. 1710 MustBeFirst = !CanNegate; 1711 } else { 1712 assert(Opcode == ISD::AND && "Must be OR or AND"); 1713 // We cannot naturally negate an AND operation. 1714 CanNegate = false; 1715 MustBeFirst = MustBeFirstL || MustBeFirstR; 1716 } 1717 return true; 1718 } 1719 return false; 1720 } 1721 1722 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain 1723 /// of CCMP/CFCMP ops. See @ref AArch64CCMP. 1724 /// Tries to transform the given i1 producing node @p Val to a series compare 1725 /// and conditional compare operations. @returns an NZCV flags producing node 1726 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if 1727 /// transformation was not possible. 1728 /// \p Negate is true if we want this sub-tree being negated just by changing 1729 /// SETCC conditions. 1730 static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val, 1731 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp, 1732 AArch64CC::CondCode Predicate) { 1733 // We're at a tree leaf, produce a conditional comparison operation. 1734 unsigned Opcode = Val->getOpcode(); 1735 if (Opcode == ISD::SETCC) { 1736 SDValue LHS = Val->getOperand(0); 1737 SDValue RHS = Val->getOperand(1); 1738 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get(); 1739 bool isInteger = LHS.getValueType().isInteger(); 1740 if (Negate) 1741 CC = getSetCCInverse(CC, isInteger); 1742 SDLoc DL(Val); 1743 // Determine OutCC and handle FP special case. 1744 if (isInteger) { 1745 OutCC = changeIntCCToAArch64CC(CC); 1746 } else { 1747 assert(LHS.getValueType().isFloatingPoint()); 1748 AArch64CC::CondCode ExtraCC; 1749 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC); 1750 // Some floating point conditions can't be tested with a single condition 1751 // code. Construct an additional comparison in this case. 1752 if (ExtraCC != AArch64CC::AL) { 1753 SDValue ExtraCmp; 1754 if (!CCOp.getNode()) 1755 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG); 1756 else 1757 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, 1758 ExtraCC, DL, DAG); 1759 CCOp = ExtraCmp; 1760 Predicate = ExtraCC; 1761 } 1762 } 1763 1764 // Produce a normal comparison if we are first in the chain 1765 if (!CCOp) 1766 return emitComparison(LHS, RHS, CC, DL, DAG); 1767 // Otherwise produce a ccmp. 1768 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL, 1769 DAG); 1770 } 1771 assert(Val->hasOneUse() && "Valid conjunction/disjunction tree"); 1772 1773 bool IsOR = Opcode == ISD::OR; 1774 1775 SDValue LHS = Val->getOperand(0); 1776 bool CanNegateL; 1777 bool MustBeFirstL; 1778 bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR); 1779 assert(ValidL && "Valid conjunction/disjunction tree"); 1780 (void)ValidL; 1781 1782 SDValue RHS = Val->getOperand(1); 1783 bool CanNegateR; 1784 bool MustBeFirstR; 1785 bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR); 1786 assert(ValidR && "Valid conjunction/disjunction tree"); 1787 (void)ValidR; 1788 1789 // Swap sub-tree that must come first to the right side. 1790 if (MustBeFirstL) { 1791 assert(!MustBeFirstR && "Valid conjunction/disjunction tree"); 1792 std::swap(LHS, RHS); 1793 std::swap(CanNegateL, CanNegateR); 1794 std::swap(MustBeFirstL, MustBeFirstR); 1795 } 1796 1797 bool NegateR; 1798 bool NegateAfterR; 1799 bool NegateL; 1800 bool NegateAfterAll; 1801 if (Opcode == ISD::OR) { 1802 // Swap the sub-tree that we can negate naturally to the left. 1803 if (!CanNegateL) { 1804 assert(CanNegateR && "at least one side must be negatable"); 1805 assert(!MustBeFirstR && "invalid conjunction/disjunction tree"); 1806 assert(!Negate); 1807 std::swap(LHS, RHS); 1808 NegateR = false; 1809 NegateAfterR = true; 1810 } else { 1811 // Negate the left sub-tree if possible, otherwise negate the result. 1812 NegateR = CanNegateR; 1813 NegateAfterR = !CanNegateR; 1814 } 1815 NegateL = true; 1816 NegateAfterAll = !Negate; 1817 } else { 1818 assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree"); 1819 assert(!Negate && "Valid conjunction/disjunction tree"); 1820 1821 NegateL = false; 1822 NegateR = false; 1823 NegateAfterR = false; 1824 NegateAfterAll = false; 1825 } 1826 1827 // Emit sub-trees. 1828 AArch64CC::CondCode RHSCC; 1829 SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate); 1830 if (NegateAfterR) 1831 RHSCC = AArch64CC::getInvertedCondCode(RHSCC); 1832 SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC); 1833 if (NegateAfterAll) 1834 OutCC = AArch64CC::getInvertedCondCode(OutCC); 1835 return CmpL; 1836 } 1837 1838 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops). 1839 /// In some cases this is even possible with OR operations in the expression. 1840 /// See \ref AArch64CCMP. 1841 /// \see emitConjunctionRec(). 1842 static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val, 1843 AArch64CC::CondCode &OutCC) { 1844 bool DummyCanNegate; 1845 bool DummyMustBeFirst; 1846 if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false)) 1847 return SDValue(); 1848 1849 return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL); 1850 } 1851 1852 /// @} 1853 1854 /// Returns how profitable it is to fold a comparison's operand's shift and/or 1855 /// extension operations. 1856 static unsigned getCmpOperandFoldingProfit(SDValue Op) { 1857 auto isSupportedExtend = [&](SDValue V) { 1858 if (V.getOpcode() == ISD::SIGN_EXTEND_INREG) 1859 return true; 1860 1861 if (V.getOpcode() == ISD::AND) 1862 if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) { 1863 uint64_t Mask = MaskCst->getZExtValue(); 1864 return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF); 1865 } 1866 1867 return false; 1868 }; 1869 1870 if (!Op.hasOneUse()) 1871 return 0; 1872 1873 if (isSupportedExtend(Op)) 1874 return 1; 1875 1876 unsigned Opc = Op.getOpcode(); 1877 if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA) 1878 if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 1879 uint64_t Shift = ShiftCst->getZExtValue(); 1880 if (isSupportedExtend(Op.getOperand(0))) 1881 return (Shift <= 4) ? 2 : 1; 1882 EVT VT = Op.getValueType(); 1883 if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63)) 1884 return 1; 1885 } 1886 1887 return 0; 1888 } 1889 1890 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC, 1891 SDValue &AArch64cc, SelectionDAG &DAG, 1892 const SDLoc &dl) { 1893 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) { 1894 EVT VT = RHS.getValueType(); 1895 uint64_t C = RHSC->getZExtValue(); 1896 if (!isLegalArithImmed(C)) { 1897 // Constant does not fit, try adjusting it by one? 1898 switch (CC) { 1899 default: 1900 break; 1901 case ISD::SETLT: 1902 case ISD::SETGE: 1903 if ((VT == MVT::i32 && C != 0x80000000 && 1904 isLegalArithImmed((uint32_t)(C - 1))) || 1905 (VT == MVT::i64 && C != 0x80000000ULL && 1906 isLegalArithImmed(C - 1ULL))) { 1907 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT; 1908 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 1909 RHS = DAG.getConstant(C, dl, VT); 1910 } 1911 break; 1912 case ISD::SETULT: 1913 case ISD::SETUGE: 1914 if ((VT == MVT::i32 && C != 0 && 1915 isLegalArithImmed((uint32_t)(C - 1))) || 1916 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) { 1917 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT; 1918 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1; 1919 RHS = DAG.getConstant(C, dl, VT); 1920 } 1921 break; 1922 case ISD::SETLE: 1923 case ISD::SETGT: 1924 if ((VT == MVT::i32 && C != INT32_MAX && 1925 isLegalArithImmed((uint32_t)(C + 1))) || 1926 (VT == MVT::i64 && C != INT64_MAX && 1927 isLegalArithImmed(C + 1ULL))) { 1928 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE; 1929 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 1930 RHS = DAG.getConstant(C, dl, VT); 1931 } 1932 break; 1933 case ISD::SETULE: 1934 case ISD::SETUGT: 1935 if ((VT == MVT::i32 && C != UINT32_MAX && 1936 isLegalArithImmed((uint32_t)(C + 1))) || 1937 (VT == MVT::i64 && C != UINT64_MAX && 1938 isLegalArithImmed(C + 1ULL))) { 1939 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE; 1940 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1; 1941 RHS = DAG.getConstant(C, dl, VT); 1942 } 1943 break; 1944 } 1945 } 1946 } 1947 1948 // Comparisons are canonicalized so that the RHS operand is simpler than the 1949 // LHS one, the extreme case being when RHS is an immediate. However, AArch64 1950 // can fold some shift+extend operations on the RHS operand, so swap the 1951 // operands if that can be done. 1952 // 1953 // For example: 1954 // lsl w13, w11, #1 1955 // cmp w13, w12 1956 // can be turned into: 1957 // cmp w12, w11, lsl #1 1958 if (!isa<ConstantSDNode>(RHS) || 1959 !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) { 1960 SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS; 1961 1962 if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) { 1963 std::swap(LHS, RHS); 1964 CC = ISD::getSetCCSwappedOperands(CC); 1965 } 1966 } 1967 1968 SDValue Cmp; 1969 AArch64CC::CondCode AArch64CC; 1970 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) { 1971 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS); 1972 1973 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095. 1974 // For the i8 operand, the largest immediate is 255, so this can be easily 1975 // encoded in the compare instruction. For the i16 operand, however, the 1976 // largest immediate cannot be encoded in the compare. 1977 // Therefore, use a sign extending load and cmn to avoid materializing the 1978 // -1 constant. For example, 1979 // movz w1, #65535 1980 // ldrh w0, [x0, #0] 1981 // cmp w0, w1 1982 // > 1983 // ldrsh w0, [x0, #0] 1984 // cmn w0, #1 1985 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS) 1986 // if and only if (sext LHS) == (sext RHS). The checks are in place to 1987 // ensure both the LHS and RHS are truly zero extended and to make sure the 1988 // transformation is profitable. 1989 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) && 1990 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD && 1991 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 && 1992 LHS.getNode()->hasNUsesOfValue(1, 0)) { 1993 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue(); 1994 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) { 1995 SDValue SExt = 1996 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS, 1997 DAG.getValueType(MVT::i16)); 1998 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl, 1999 RHS.getValueType()), 2000 CC, dl, DAG); 2001 AArch64CC = changeIntCCToAArch64CC(CC); 2002 } 2003 } 2004 2005 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) { 2006 if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) { 2007 if ((CC == ISD::SETNE) ^ RHSC->isNullValue()) 2008 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC); 2009 } 2010 } 2011 } 2012 2013 if (!Cmp) { 2014 Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 2015 AArch64CC = changeIntCCToAArch64CC(CC); 2016 } 2017 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC); 2018 return Cmp; 2019 } 2020 2021 static std::pair<SDValue, SDValue> 2022 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) { 2023 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) && 2024 "Unsupported value type"); 2025 SDValue Value, Overflow; 2026 SDLoc DL(Op); 2027 SDValue LHS = Op.getOperand(0); 2028 SDValue RHS = Op.getOperand(1); 2029 unsigned Opc = 0; 2030 switch (Op.getOpcode()) { 2031 default: 2032 llvm_unreachable("Unknown overflow instruction!"); 2033 case ISD::SADDO: 2034 Opc = AArch64ISD::ADDS; 2035 CC = AArch64CC::VS; 2036 break; 2037 case ISD::UADDO: 2038 Opc = AArch64ISD::ADDS; 2039 CC = AArch64CC::HS; 2040 break; 2041 case ISD::SSUBO: 2042 Opc = AArch64ISD::SUBS; 2043 CC = AArch64CC::VS; 2044 break; 2045 case ISD::USUBO: 2046 Opc = AArch64ISD::SUBS; 2047 CC = AArch64CC::LO; 2048 break; 2049 // Multiply needs a little bit extra work. 2050 case ISD::SMULO: 2051 case ISD::UMULO: { 2052 CC = AArch64CC::NE; 2053 bool IsSigned = Op.getOpcode() == ISD::SMULO; 2054 if (Op.getValueType() == MVT::i32) { 2055 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 2056 // For a 32 bit multiply with overflow check we want the instruction 2057 // selector to generate a widening multiply (SMADDL/UMADDL). For that we 2058 // need to generate the following pattern: 2059 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b)) 2060 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS); 2061 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS); 2062 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 2063 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul, 2064 DAG.getConstant(0, DL, MVT::i64)); 2065 // On AArch64 the upper 32 bits are always zero extended for a 32 bit 2066 // operation. We need to clear out the upper 32 bits, because we used a 2067 // widening multiply that wrote all 64 bits. In the end this should be a 2068 // noop. 2069 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add); 2070 if (IsSigned) { 2071 // The signed overflow check requires more than just a simple check for 2072 // any bit set in the upper 32 bits of the result. These bits could be 2073 // just the sign bits of a negative number. To perform the overflow 2074 // check we have to arithmetic shift right the 32nd bit of the result by 2075 // 31 bits. Then we compare the result to the upper 32 bits. 2076 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add, 2077 DAG.getConstant(32, DL, MVT::i64)); 2078 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits); 2079 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value, 2080 DAG.getConstant(31, DL, MVT::i64)); 2081 // It is important that LowerBits is last, otherwise the arithmetic 2082 // shift will not be folded into the compare (SUBS). 2083 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32); 2084 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 2085 .getValue(1); 2086 } else { 2087 // The overflow check for unsigned multiply is easy. We only need to 2088 // check if any of the upper 32 bits are set. This can be done with a 2089 // CMP (shifted register). For that we need to generate the following 2090 // pattern: 2091 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32) 2092 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul, 2093 DAG.getConstant(32, DL, MVT::i64)); 2094 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 2095 Overflow = 2096 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 2097 DAG.getConstant(0, DL, MVT::i64), 2098 UpperBits).getValue(1); 2099 } 2100 break; 2101 } 2102 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type"); 2103 // For the 64 bit multiply 2104 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS); 2105 if (IsSigned) { 2106 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS); 2107 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value, 2108 DAG.getConstant(63, DL, MVT::i64)); 2109 // It is important that LowerBits is last, otherwise the arithmetic 2110 // shift will not be folded into the compare (SUBS). 2111 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 2112 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits) 2113 .getValue(1); 2114 } else { 2115 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS); 2116 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32); 2117 Overflow = 2118 DAG.getNode(AArch64ISD::SUBS, DL, VTs, 2119 DAG.getConstant(0, DL, MVT::i64), 2120 UpperBits).getValue(1); 2121 } 2122 break; 2123 } 2124 } // switch (...) 2125 2126 if (Opc) { 2127 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32); 2128 2129 // Emit the AArch64 operation with overflow check. 2130 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS); 2131 Overflow = Value.getValue(1); 2132 } 2133 return std::make_pair(Value, Overflow); 2134 } 2135 2136 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG, 2137 RTLIB::Libcall Call) const { 2138 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end()); 2139 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first; 2140 } 2141 2142 // Returns true if the given Op is the overflow flag result of an overflow 2143 // intrinsic operation. 2144 static bool isOverflowIntrOpRes(SDValue Op) { 2145 unsigned Opc = Op.getOpcode(); 2146 return (Op.getResNo() == 1 && 2147 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO || 2148 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)); 2149 } 2150 2151 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) { 2152 SDValue Sel = Op.getOperand(0); 2153 SDValue Other = Op.getOperand(1); 2154 SDLoc dl(Sel); 2155 2156 // If the operand is an overflow checking operation, invert the condition 2157 // code and kill the Not operation. I.e., transform: 2158 // (xor (overflow_op_bool, 1)) 2159 // --> 2160 // (csel 1, 0, invert(cc), overflow_op_bool) 2161 // ... which later gets transformed to just a cset instruction with an 2162 // inverted condition code, rather than a cset + eor sequence. 2163 if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) { 2164 // Only lower legal XALUO ops. 2165 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0))) 2166 return SDValue(); 2167 2168 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 2169 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 2170 AArch64CC::CondCode CC; 2171 SDValue Value, Overflow; 2172 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG); 2173 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); 2174 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal, 2175 CCVal, Overflow); 2176 } 2177 // If neither operand is a SELECT_CC, give up. 2178 if (Sel.getOpcode() != ISD::SELECT_CC) 2179 std::swap(Sel, Other); 2180 if (Sel.getOpcode() != ISD::SELECT_CC) 2181 return Op; 2182 2183 // The folding we want to perform is: 2184 // (xor x, (select_cc a, b, cc, 0, -1) ) 2185 // --> 2186 // (csel x, (xor x, -1), cc ...) 2187 // 2188 // The latter will get matched to a CSINV instruction. 2189 2190 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get(); 2191 SDValue LHS = Sel.getOperand(0); 2192 SDValue RHS = Sel.getOperand(1); 2193 SDValue TVal = Sel.getOperand(2); 2194 SDValue FVal = Sel.getOperand(3); 2195 2196 // FIXME: This could be generalized to non-integer comparisons. 2197 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 2198 return Op; 2199 2200 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 2201 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 2202 2203 // The values aren't constants, this isn't the pattern we're looking for. 2204 if (!CFVal || !CTVal) 2205 return Op; 2206 2207 // We can commute the SELECT_CC by inverting the condition. This 2208 // might be needed to make this fit into a CSINV pattern. 2209 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) { 2210 std::swap(TVal, FVal); 2211 std::swap(CTVal, CFVal); 2212 CC = ISD::getSetCCInverse(CC, true); 2213 } 2214 2215 // If the constants line up, perform the transform! 2216 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) { 2217 SDValue CCVal; 2218 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 2219 2220 FVal = Other; 2221 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other, 2222 DAG.getConstant(-1ULL, dl, Other.getValueType())); 2223 2224 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal, 2225 CCVal, Cmp); 2226 } 2227 2228 return Op; 2229 } 2230 2231 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) { 2232 EVT VT = Op.getValueType(); 2233 2234 // Let legalize expand this if it isn't a legal type yet. 2235 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 2236 return SDValue(); 2237 2238 SDVTList VTs = DAG.getVTList(VT, MVT::i32); 2239 2240 unsigned Opc; 2241 bool ExtraOp = false; 2242 switch (Op.getOpcode()) { 2243 default: 2244 llvm_unreachable("Invalid code"); 2245 case ISD::ADDC: 2246 Opc = AArch64ISD::ADDS; 2247 break; 2248 case ISD::SUBC: 2249 Opc = AArch64ISD::SUBS; 2250 break; 2251 case ISD::ADDE: 2252 Opc = AArch64ISD::ADCS; 2253 ExtraOp = true; 2254 break; 2255 case ISD::SUBE: 2256 Opc = AArch64ISD::SBCS; 2257 ExtraOp = true; 2258 break; 2259 } 2260 2261 if (!ExtraOp) 2262 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1)); 2263 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1), 2264 Op.getOperand(2)); 2265 } 2266 2267 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) { 2268 // Let legalize expand this if it isn't a legal type yet. 2269 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType())) 2270 return SDValue(); 2271 2272 SDLoc dl(Op); 2273 AArch64CC::CondCode CC; 2274 // The actual operation that sets the overflow or carry flag. 2275 SDValue Value, Overflow; 2276 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG); 2277 2278 // We use 0 and 1 as false and true values. 2279 SDValue TVal = DAG.getConstant(1, dl, MVT::i32); 2280 SDValue FVal = DAG.getConstant(0, dl, MVT::i32); 2281 2282 // We use an inverted condition, because the conditional select is inverted 2283 // too. This will allow it to be selected to a single instruction: 2284 // CSINC Wd, WZR, WZR, invert(cond). 2285 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32); 2286 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal, 2287 CCVal, Overflow); 2288 2289 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32); 2290 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow); 2291 } 2292 2293 // Prefetch operands are: 2294 // 1: Address to prefetch 2295 // 2: bool isWrite 2296 // 3: int locality (0 = no locality ... 3 = extreme locality) 2297 // 4: bool isDataCache 2298 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) { 2299 SDLoc DL(Op); 2300 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 2301 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue(); 2302 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue(); 2303 2304 bool IsStream = !Locality; 2305 // When the locality number is set 2306 if (Locality) { 2307 // The front-end should have filtered out the out-of-range values 2308 assert(Locality <= 3 && "Prefetch locality out-of-range"); 2309 // The locality degree is the opposite of the cache speed. 2310 // Put the number the other way around. 2311 // The encoding starts at 0 for level 1 2312 Locality = 3 - Locality; 2313 } 2314 2315 // built the mask value encoding the expected behavior. 2316 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit 2317 (!IsData << 3) | // IsDataCache bit 2318 (Locality << 1) | // Cache level bits 2319 (unsigned)IsStream; // Stream bit 2320 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0), 2321 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1)); 2322 } 2323 2324 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op, 2325 SelectionDAG &DAG) const { 2326 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering"); 2327 2328 RTLIB::Libcall LC; 2329 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType()); 2330 2331 return LowerF128Call(Op, DAG, LC); 2332 } 2333 2334 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op, 2335 SelectionDAG &DAG) const { 2336 if (Op.getOperand(0).getValueType() != MVT::f128) { 2337 // It's legal except when f128 is involved 2338 return Op; 2339 } 2340 2341 RTLIB::Libcall LC; 2342 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType()); 2343 2344 // FP_ROUND node has a second operand indicating whether it is known to be 2345 // precise. That doesn't take part in the LibCall so we can't directly use 2346 // LowerF128Call. 2347 SDValue SrcVal = Op.getOperand(0); 2348 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false, 2349 SDLoc(Op)).first; 2350 } 2351 2352 SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op, 2353 SelectionDAG &DAG) const { 2354 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 2355 // Any additional optimization in this function should be recorded 2356 // in the cost tables. 2357 EVT InVT = Op.getOperand(0).getValueType(); 2358 EVT VT = Op.getValueType(); 2359 unsigned NumElts = InVT.getVectorNumElements(); 2360 2361 // f16 conversions are promoted to f32 when full fp16 is not supported. 2362 if (InVT.getVectorElementType() == MVT::f16 && 2363 !Subtarget->hasFullFP16()) { 2364 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts); 2365 SDLoc dl(Op); 2366 return DAG.getNode( 2367 Op.getOpcode(), dl, Op.getValueType(), 2368 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0))); 2369 } 2370 2371 if (VT.getSizeInBits() < InVT.getSizeInBits()) { 2372 SDLoc dl(Op); 2373 SDValue Cv = 2374 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(), 2375 Op.getOperand(0)); 2376 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv); 2377 } 2378 2379 if (VT.getSizeInBits() > InVT.getSizeInBits()) { 2380 SDLoc dl(Op); 2381 MVT ExtVT = 2382 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()), 2383 VT.getVectorNumElements()); 2384 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0)); 2385 return DAG.getNode(Op.getOpcode(), dl, VT, Ext); 2386 } 2387 2388 // Type changing conversions are illegal. 2389 return Op; 2390 } 2391 2392 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op, 2393 SelectionDAG &DAG) const { 2394 if (Op.getOperand(0).getValueType().isVector()) 2395 return LowerVectorFP_TO_INT(Op, DAG); 2396 2397 // f16 conversions are promoted to f32 when full fp16 is not supported. 2398 if (Op.getOperand(0).getValueType() == MVT::f16 && 2399 !Subtarget->hasFullFP16()) { 2400 SDLoc dl(Op); 2401 return DAG.getNode( 2402 Op.getOpcode(), dl, Op.getValueType(), 2403 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0))); 2404 } 2405 2406 if (Op.getOperand(0).getValueType() != MVT::f128) { 2407 // It's legal except when f128 is involved 2408 return Op; 2409 } 2410 2411 RTLIB::Libcall LC; 2412 if (Op.getOpcode() == ISD::FP_TO_SINT) 2413 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType()); 2414 else 2415 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType()); 2416 2417 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end()); 2418 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first; 2419 } 2420 2421 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) { 2422 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp. 2423 // Any additional optimization in this function should be recorded 2424 // in the cost tables. 2425 EVT VT = Op.getValueType(); 2426 SDLoc dl(Op); 2427 SDValue In = Op.getOperand(0); 2428 EVT InVT = In.getValueType(); 2429 2430 if (VT.getSizeInBits() < InVT.getSizeInBits()) { 2431 MVT CastVT = 2432 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()), 2433 InVT.getVectorNumElements()); 2434 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In); 2435 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl)); 2436 } 2437 2438 if (VT.getSizeInBits() > InVT.getSizeInBits()) { 2439 unsigned CastOpc = 2440 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 2441 EVT CastVT = VT.changeVectorElementTypeToInteger(); 2442 In = DAG.getNode(CastOpc, dl, CastVT, In); 2443 return DAG.getNode(Op.getOpcode(), dl, VT, In); 2444 } 2445 2446 return Op; 2447 } 2448 2449 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op, 2450 SelectionDAG &DAG) const { 2451 if (Op.getValueType().isVector()) 2452 return LowerVectorINT_TO_FP(Op, DAG); 2453 2454 // f16 conversions are promoted to f32 when full fp16 is not supported. 2455 if (Op.getValueType() == MVT::f16 && 2456 !Subtarget->hasFullFP16()) { 2457 SDLoc dl(Op); 2458 return DAG.getNode( 2459 ISD::FP_ROUND, dl, MVT::f16, 2460 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)), 2461 DAG.getIntPtrConstant(0, dl)); 2462 } 2463 2464 // i128 conversions are libcalls. 2465 if (Op.getOperand(0).getValueType() == MVT::i128) 2466 return SDValue(); 2467 2468 // Other conversions are legal, unless it's to the completely software-based 2469 // fp128. 2470 if (Op.getValueType() != MVT::f128) 2471 return Op; 2472 2473 RTLIB::Libcall LC; 2474 if (Op.getOpcode() == ISD::SINT_TO_FP) 2475 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType()); 2476 else 2477 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType()); 2478 2479 return LowerF128Call(Op, DAG, LC); 2480 } 2481 2482 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op, 2483 SelectionDAG &DAG) const { 2484 // For iOS, we want to call an alternative entry point: __sincos_stret, 2485 // which returns the values in two S / D registers. 2486 SDLoc dl(Op); 2487 SDValue Arg = Op.getOperand(0); 2488 EVT ArgVT = Arg.getValueType(); 2489 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext()); 2490 2491 ArgListTy Args; 2492 ArgListEntry Entry; 2493 2494 Entry.Node = Arg; 2495 Entry.Ty = ArgTy; 2496 Entry.IsSExt = false; 2497 Entry.IsZExt = false; 2498 Args.push_back(Entry); 2499 2500 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64 2501 : RTLIB::SINCOS_STRET_F32; 2502 const char *LibcallName = getLibcallName(LC); 2503 SDValue Callee = 2504 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout())); 2505 2506 StructType *RetTy = StructType::get(ArgTy, ArgTy); 2507 TargetLowering::CallLoweringInfo CLI(DAG); 2508 CLI.setDebugLoc(dl) 2509 .setChain(DAG.getEntryNode()) 2510 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args)); 2511 2512 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI); 2513 return CallResult.first; 2514 } 2515 2516 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) { 2517 if (Op.getValueType() != MVT::f16) 2518 return SDValue(); 2519 2520 assert(Op.getOperand(0).getValueType() == MVT::i16); 2521 SDLoc DL(Op); 2522 2523 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0)); 2524 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op); 2525 return SDValue( 2526 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op, 2527 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 2528 0); 2529 } 2530 2531 static EVT getExtensionTo64Bits(const EVT &OrigVT) { 2532 if (OrigVT.getSizeInBits() >= 64) 2533 return OrigVT; 2534 2535 assert(OrigVT.isSimple() && "Expecting a simple value type"); 2536 2537 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy; 2538 switch (OrigSimpleTy) { 2539 default: llvm_unreachable("Unexpected Vector Type"); 2540 case MVT::v2i8: 2541 case MVT::v2i16: 2542 return MVT::v2i32; 2543 case MVT::v4i8: 2544 return MVT::v4i16; 2545 } 2546 } 2547 2548 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG, 2549 const EVT &OrigTy, 2550 const EVT &ExtTy, 2551 unsigned ExtOpcode) { 2552 // The vector originally had a size of OrigTy. It was then extended to ExtTy. 2553 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than 2554 // 64-bits we need to insert a new extension so that it will be 64-bits. 2555 assert(ExtTy.is128BitVector() && "Unexpected extension size"); 2556 if (OrigTy.getSizeInBits() >= 64) 2557 return N; 2558 2559 // Must extend size to at least 64 bits to be used as an operand for VMULL. 2560 EVT NewVT = getExtensionTo64Bits(OrigTy); 2561 2562 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N); 2563 } 2564 2565 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG, 2566 bool isSigned) { 2567 EVT VT = N->getValueType(0); 2568 2569 if (N->getOpcode() != ISD::BUILD_VECTOR) 2570 return false; 2571 2572 for (const SDValue &Elt : N->op_values()) { 2573 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) { 2574 unsigned EltSize = VT.getScalarSizeInBits(); 2575 unsigned HalfSize = EltSize / 2; 2576 if (isSigned) { 2577 if (!isIntN(HalfSize, C->getSExtValue())) 2578 return false; 2579 } else { 2580 if (!isUIntN(HalfSize, C->getZExtValue())) 2581 return false; 2582 } 2583 continue; 2584 } 2585 return false; 2586 } 2587 2588 return true; 2589 } 2590 2591 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) { 2592 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND) 2593 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG, 2594 N->getOperand(0)->getValueType(0), 2595 N->getValueType(0), 2596 N->getOpcode()); 2597 2598 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR"); 2599 EVT VT = N->getValueType(0); 2600 SDLoc dl(N); 2601 unsigned EltSize = VT.getScalarSizeInBits() / 2; 2602 unsigned NumElts = VT.getVectorNumElements(); 2603 MVT TruncVT = MVT::getIntegerVT(EltSize); 2604 SmallVector<SDValue, 8> Ops; 2605 for (unsigned i = 0; i != NumElts; ++i) { 2606 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i)); 2607 const APInt &CInt = C->getAPIntValue(); 2608 // Element types smaller than 32 bits are not legal, so use i32 elements. 2609 // The values are implicitly truncated so sext vs. zext doesn't matter. 2610 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32)); 2611 } 2612 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops); 2613 } 2614 2615 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) { 2616 return N->getOpcode() == ISD::SIGN_EXTEND || 2617 isExtendedBUILD_VECTOR(N, DAG, true); 2618 } 2619 2620 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) { 2621 return N->getOpcode() == ISD::ZERO_EXTEND || 2622 isExtendedBUILD_VECTOR(N, DAG, false); 2623 } 2624 2625 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) { 2626 unsigned Opcode = N->getOpcode(); 2627 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 2628 SDNode *N0 = N->getOperand(0).getNode(); 2629 SDNode *N1 = N->getOperand(1).getNode(); 2630 return N0->hasOneUse() && N1->hasOneUse() && 2631 isSignExtended(N0, DAG) && isSignExtended(N1, DAG); 2632 } 2633 return false; 2634 } 2635 2636 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) { 2637 unsigned Opcode = N->getOpcode(); 2638 if (Opcode == ISD::ADD || Opcode == ISD::SUB) { 2639 SDNode *N0 = N->getOperand(0).getNode(); 2640 SDNode *N1 = N->getOperand(1).getNode(); 2641 return N0->hasOneUse() && N1->hasOneUse() && 2642 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG); 2643 } 2644 return false; 2645 } 2646 2647 SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op, 2648 SelectionDAG &DAG) const { 2649 // The rounding mode is in bits 23:22 of the FPSCR. 2650 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0 2651 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3) 2652 // so that the shift + and get folded into a bitfield extract. 2653 SDLoc dl(Op); 2654 2655 SDValue FPCR_64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i64, 2656 DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl, 2657 MVT::i64)); 2658 SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64); 2659 SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32, 2660 DAG.getConstant(1U << 22, dl, MVT::i32)); 2661 SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds, 2662 DAG.getConstant(22, dl, MVT::i32)); 2663 return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE, 2664 DAG.getConstant(3, dl, MVT::i32)); 2665 } 2666 2667 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) { 2668 // Multiplications are only custom-lowered for 128-bit vectors so that 2669 // VMULL can be detected. Otherwise v2i64 multiplications are not legal. 2670 EVT VT = Op.getValueType(); 2671 assert(VT.is128BitVector() && VT.isInteger() && 2672 "unexpected type for custom-lowering ISD::MUL"); 2673 SDNode *N0 = Op.getOperand(0).getNode(); 2674 SDNode *N1 = Op.getOperand(1).getNode(); 2675 unsigned NewOpc = 0; 2676 bool isMLA = false; 2677 bool isN0SExt = isSignExtended(N0, DAG); 2678 bool isN1SExt = isSignExtended(N1, DAG); 2679 if (isN0SExt && isN1SExt) 2680 NewOpc = AArch64ISD::SMULL; 2681 else { 2682 bool isN0ZExt = isZeroExtended(N0, DAG); 2683 bool isN1ZExt = isZeroExtended(N1, DAG); 2684 if (isN0ZExt && isN1ZExt) 2685 NewOpc = AArch64ISD::UMULL; 2686 else if (isN1SExt || isN1ZExt) { 2687 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these 2688 // into (s/zext A * s/zext C) + (s/zext B * s/zext C) 2689 if (isN1SExt && isAddSubSExt(N0, DAG)) { 2690 NewOpc = AArch64ISD::SMULL; 2691 isMLA = true; 2692 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) { 2693 NewOpc = AArch64ISD::UMULL; 2694 isMLA = true; 2695 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) { 2696 std::swap(N0, N1); 2697 NewOpc = AArch64ISD::UMULL; 2698 isMLA = true; 2699 } 2700 } 2701 2702 if (!NewOpc) { 2703 if (VT == MVT::v2i64) 2704 // Fall through to expand this. It is not legal. 2705 return SDValue(); 2706 else 2707 // Other vector multiplications are legal. 2708 return Op; 2709 } 2710 } 2711 2712 // Legalize to a S/UMULL instruction 2713 SDLoc DL(Op); 2714 SDValue Op0; 2715 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG); 2716 if (!isMLA) { 2717 Op0 = skipExtensionForVectorMULL(N0, DAG); 2718 assert(Op0.getValueType().is64BitVector() && 2719 Op1.getValueType().is64BitVector() && 2720 "unexpected types for extended operands to VMULL"); 2721 return DAG.getNode(NewOpc, DL, VT, Op0, Op1); 2722 } 2723 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during 2724 // isel lowering to take advantage of no-stall back to back s/umul + s/umla. 2725 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57 2726 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG); 2727 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG); 2728 EVT Op1VT = Op1.getValueType(); 2729 return DAG.getNode(N0->getOpcode(), DL, VT, 2730 DAG.getNode(NewOpc, DL, VT, 2731 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1), 2732 DAG.getNode(NewOpc, DL, VT, 2733 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1)); 2734 } 2735 2736 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 2737 SelectionDAG &DAG) const { 2738 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 2739 SDLoc dl(Op); 2740 switch (IntNo) { 2741 default: return SDValue(); // Don't custom lower most intrinsics. 2742 case Intrinsic::thread_pointer: { 2743 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 2744 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT); 2745 } 2746 case Intrinsic::aarch64_neon_abs: { 2747 EVT Ty = Op.getValueType(); 2748 if (Ty == MVT::i64) { 2749 SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, 2750 Op.getOperand(1)); 2751 Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result); 2752 return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result); 2753 } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) { 2754 return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1)); 2755 } else { 2756 report_fatal_error("Unexpected type for AArch64 NEON intrinic"); 2757 } 2758 } 2759 case Intrinsic::aarch64_neon_smax: 2760 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(), 2761 Op.getOperand(1), Op.getOperand(2)); 2762 case Intrinsic::aarch64_neon_umax: 2763 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(), 2764 Op.getOperand(1), Op.getOperand(2)); 2765 case Intrinsic::aarch64_neon_smin: 2766 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(), 2767 Op.getOperand(1), Op.getOperand(2)); 2768 case Intrinsic::aarch64_neon_umin: 2769 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(), 2770 Op.getOperand(1), Op.getOperand(2)); 2771 2772 case Intrinsic::localaddress: { 2773 const auto &MF = DAG.getMachineFunction(); 2774 const auto *RegInfo = Subtarget->getRegisterInfo(); 2775 unsigned Reg = RegInfo->getLocalAddressRegister(MF); 2776 return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, 2777 Op.getSimpleValueType()); 2778 } 2779 2780 case Intrinsic::eh_recoverfp: { 2781 // FIXME: This needs to be implemented to correctly handle highly aligned 2782 // stack objects. For now we simply return the incoming FP. Refer D53541 2783 // for more details. 2784 SDValue FnOp = Op.getOperand(1); 2785 SDValue IncomingFPOp = Op.getOperand(2); 2786 GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp); 2787 auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr); 2788 if (!Fn) 2789 report_fatal_error( 2790 "llvm.eh.recoverfp must take a function as the first argument"); 2791 return IncomingFPOp; 2792 } 2793 } 2794 } 2795 2796 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16. 2797 static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST, 2798 EVT VT, EVT MemVT, 2799 SelectionDAG &DAG) { 2800 assert(VT.isVector() && "VT should be a vector type"); 2801 assert(MemVT == MVT::v4i8 && VT == MVT::v4i16); 2802 2803 SDValue Value = ST->getValue(); 2804 2805 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract 2806 // the word lane which represent the v4i8 subvector. It optimizes the store 2807 // to: 2808 // 2809 // xtn v0.8b, v0.8h 2810 // str s0, [x0] 2811 2812 SDValue Undef = DAG.getUNDEF(MVT::i16); 2813 SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL, 2814 {Undef, Undef, Undef, Undef}); 2815 2816 SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16, 2817 Value, UndefVec); 2818 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt); 2819 2820 Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc); 2821 SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, 2822 Trunc, DAG.getConstant(0, DL, MVT::i64)); 2823 2824 return DAG.getStore(ST->getChain(), DL, ExtractTrunc, 2825 ST->getBasePtr(), ST->getMemOperand()); 2826 } 2827 2828 // Custom lowering for any store, vector or scalar and/or default or with 2829 // a truncate operations. Currently only custom lower truncate operation 2830 // from vector v4i16 to v4i8. 2831 SDValue AArch64TargetLowering::LowerSTORE(SDValue Op, 2832 SelectionDAG &DAG) const { 2833 SDLoc Dl(Op); 2834 StoreSDNode *StoreNode = cast<StoreSDNode>(Op); 2835 assert (StoreNode && "Can only custom lower store nodes"); 2836 2837 SDValue Value = StoreNode->getValue(); 2838 2839 EVT VT = Value.getValueType(); 2840 EVT MemVT = StoreNode->getMemoryVT(); 2841 2842 assert (VT.isVector() && "Can only custom lower vector store types"); 2843 2844 unsigned AS = StoreNode->getAddressSpace(); 2845 unsigned Align = StoreNode->getAlignment(); 2846 if (Align < MemVT.getStoreSize() && 2847 !allowsMisalignedMemoryAccesses( 2848 MemVT, AS, Align, StoreNode->getMemOperand()->getFlags(), nullptr)) { 2849 return scalarizeVectorStore(StoreNode, DAG); 2850 } 2851 2852 if (StoreNode->isTruncatingStore()) { 2853 return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG); 2854 } 2855 2856 return SDValue(); 2857 } 2858 2859 SDValue AArch64TargetLowering::LowerOperation(SDValue Op, 2860 SelectionDAG &DAG) const { 2861 LLVM_DEBUG(dbgs() << "Custom lowering: "); 2862 LLVM_DEBUG(Op.dump()); 2863 2864 switch (Op.getOpcode()) { 2865 default: 2866 llvm_unreachable("unimplemented operand"); 2867 return SDValue(); 2868 case ISD::BITCAST: 2869 return LowerBITCAST(Op, DAG); 2870 case ISD::GlobalAddress: 2871 return LowerGlobalAddress(Op, DAG); 2872 case ISD::GlobalTLSAddress: 2873 return LowerGlobalTLSAddress(Op, DAG); 2874 case ISD::SETCC: 2875 return LowerSETCC(Op, DAG); 2876 case ISD::BR_CC: 2877 return LowerBR_CC(Op, DAG); 2878 case ISD::SELECT: 2879 return LowerSELECT(Op, DAG); 2880 case ISD::SELECT_CC: 2881 return LowerSELECT_CC(Op, DAG); 2882 case ISD::JumpTable: 2883 return LowerJumpTable(Op, DAG); 2884 case ISD::BR_JT: 2885 return LowerBR_JT(Op, DAG); 2886 case ISD::ConstantPool: 2887 return LowerConstantPool(Op, DAG); 2888 case ISD::BlockAddress: 2889 return LowerBlockAddress(Op, DAG); 2890 case ISD::VASTART: 2891 return LowerVASTART(Op, DAG); 2892 case ISD::VACOPY: 2893 return LowerVACOPY(Op, DAG); 2894 case ISD::VAARG: 2895 return LowerVAARG(Op, DAG); 2896 case ISD::ADDC: 2897 case ISD::ADDE: 2898 case ISD::SUBC: 2899 case ISD::SUBE: 2900 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG); 2901 case ISD::SADDO: 2902 case ISD::UADDO: 2903 case ISD::SSUBO: 2904 case ISD::USUBO: 2905 case ISD::SMULO: 2906 case ISD::UMULO: 2907 return LowerXALUO(Op, DAG); 2908 case ISD::FADD: 2909 return LowerF128Call(Op, DAG, RTLIB::ADD_F128); 2910 case ISD::FSUB: 2911 return LowerF128Call(Op, DAG, RTLIB::SUB_F128); 2912 case ISD::FMUL: 2913 return LowerF128Call(Op, DAG, RTLIB::MUL_F128); 2914 case ISD::FDIV: 2915 return LowerF128Call(Op, DAG, RTLIB::DIV_F128); 2916 case ISD::FP_ROUND: 2917 return LowerFP_ROUND(Op, DAG); 2918 case ISD::FP_EXTEND: 2919 return LowerFP_EXTEND(Op, DAG); 2920 case ISD::FRAMEADDR: 2921 return LowerFRAMEADDR(Op, DAG); 2922 case ISD::SPONENTRY: 2923 return LowerSPONENTRY(Op, DAG); 2924 case ISD::RETURNADDR: 2925 return LowerRETURNADDR(Op, DAG); 2926 case ISD::ADDROFRETURNADDR: 2927 return LowerADDROFRETURNADDR(Op, DAG); 2928 case ISD::INSERT_VECTOR_ELT: 2929 return LowerINSERT_VECTOR_ELT(Op, DAG); 2930 case ISD::EXTRACT_VECTOR_ELT: 2931 return LowerEXTRACT_VECTOR_ELT(Op, DAG); 2932 case ISD::BUILD_VECTOR: 2933 return LowerBUILD_VECTOR(Op, DAG); 2934 case ISD::VECTOR_SHUFFLE: 2935 return LowerVECTOR_SHUFFLE(Op, DAG); 2936 case ISD::EXTRACT_SUBVECTOR: 2937 return LowerEXTRACT_SUBVECTOR(Op, DAG); 2938 case ISD::SRA: 2939 case ISD::SRL: 2940 case ISD::SHL: 2941 return LowerVectorSRA_SRL_SHL(Op, DAG); 2942 case ISD::SHL_PARTS: 2943 return LowerShiftLeftParts(Op, DAG); 2944 case ISD::SRL_PARTS: 2945 case ISD::SRA_PARTS: 2946 return LowerShiftRightParts(Op, DAG); 2947 case ISD::CTPOP: 2948 return LowerCTPOP(Op, DAG); 2949 case ISD::FCOPYSIGN: 2950 return LowerFCOPYSIGN(Op, DAG); 2951 case ISD::OR: 2952 return LowerVectorOR(Op, DAG); 2953 case ISD::XOR: 2954 return LowerXOR(Op, DAG); 2955 case ISD::PREFETCH: 2956 return LowerPREFETCH(Op, DAG); 2957 case ISD::SINT_TO_FP: 2958 case ISD::UINT_TO_FP: 2959 return LowerINT_TO_FP(Op, DAG); 2960 case ISD::FP_TO_SINT: 2961 case ISD::FP_TO_UINT: 2962 return LowerFP_TO_INT(Op, DAG); 2963 case ISD::FSINCOS: 2964 return LowerFSINCOS(Op, DAG); 2965 case ISD::FLT_ROUNDS_: 2966 return LowerFLT_ROUNDS_(Op, DAG); 2967 case ISD::MUL: 2968 return LowerMUL(Op, DAG); 2969 case ISD::INTRINSIC_WO_CHAIN: 2970 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2971 case ISD::STORE: 2972 return LowerSTORE(Op, DAG); 2973 case ISD::VECREDUCE_ADD: 2974 case ISD::VECREDUCE_SMAX: 2975 case ISD::VECREDUCE_SMIN: 2976 case ISD::VECREDUCE_UMAX: 2977 case ISD::VECREDUCE_UMIN: 2978 case ISD::VECREDUCE_FMAX: 2979 case ISD::VECREDUCE_FMIN: 2980 return LowerVECREDUCE(Op, DAG); 2981 case ISD::ATOMIC_LOAD_SUB: 2982 return LowerATOMIC_LOAD_SUB(Op, DAG); 2983 case ISD::ATOMIC_LOAD_AND: 2984 return LowerATOMIC_LOAD_AND(Op, DAG); 2985 case ISD::DYNAMIC_STACKALLOC: 2986 return LowerDYNAMIC_STACKALLOC(Op, DAG); 2987 } 2988 } 2989 2990 //===----------------------------------------------------------------------===// 2991 // Calling Convention Implementation 2992 //===----------------------------------------------------------------------===// 2993 2994 /// Selects the correct CCAssignFn for a given CallingConvention value. 2995 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC, 2996 bool IsVarArg) const { 2997 switch (CC) { 2998 default: 2999 report_fatal_error("Unsupported calling convention."); 3000 case CallingConv::WebKit_JS: 3001 return CC_AArch64_WebKit_JS; 3002 case CallingConv::GHC: 3003 return CC_AArch64_GHC; 3004 case CallingConv::C: 3005 case CallingConv::Fast: 3006 case CallingConv::PreserveMost: 3007 case CallingConv::CXX_FAST_TLS: 3008 case CallingConv::Swift: 3009 if (Subtarget->isTargetWindows() && IsVarArg) 3010 return CC_AArch64_Win64_VarArg; 3011 if (!Subtarget->isTargetDarwin()) 3012 return CC_AArch64_AAPCS; 3013 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS; 3014 case CallingConv::Win64: 3015 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS; 3016 case CallingConv::AArch64_VectorCall: 3017 return CC_AArch64_AAPCS; 3018 } 3019 } 3020 3021 CCAssignFn * 3022 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const { 3023 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS 3024 : RetCC_AArch64_AAPCS; 3025 } 3026 3027 SDValue AArch64TargetLowering::LowerFormalArguments( 3028 SDValue Chain, CallingConv::ID CallConv, bool isVarArg, 3029 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 3030 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 3031 MachineFunction &MF = DAG.getMachineFunction(); 3032 MachineFrameInfo &MFI = MF.getFrameInfo(); 3033 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()); 3034 3035 // Assign locations to all of the incoming arguments. 3036 SmallVector<CCValAssign, 16> ArgLocs; 3037 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs, 3038 *DAG.getContext()); 3039 3040 // At this point, Ins[].VT may already be promoted to i32. To correctly 3041 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 3042 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 3043 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here 3044 // we use a special version of AnalyzeFormalArguments to pass in ValVT and 3045 // LocVT. 3046 unsigned NumArgs = Ins.size(); 3047 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin(); 3048 unsigned CurArgIdx = 0; 3049 for (unsigned i = 0; i != NumArgs; ++i) { 3050 MVT ValVT = Ins[i].VT; 3051 if (Ins[i].isOrigArg()) { 3052 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx); 3053 CurArgIdx = Ins[i].getOrigArgIndex(); 3054 3055 // Get type of the original argument. 3056 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(), 3057 /*AllowUnknown*/ true); 3058 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other; 3059 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 3060 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 3061 ValVT = MVT::i8; 3062 else if (ActualMVT == MVT::i16) 3063 ValVT = MVT::i16; 3064 } 3065 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 3066 bool Res = 3067 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo); 3068 assert(!Res && "Call operand has unhandled type"); 3069 (void)Res; 3070 } 3071 assert(ArgLocs.size() == Ins.size()); 3072 SmallVector<SDValue, 16> ArgValues; 3073 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 3074 CCValAssign &VA = ArgLocs[i]; 3075 3076 if (Ins[i].Flags.isByVal()) { 3077 // Byval is used for HFAs in the PCS, but the system should work in a 3078 // non-compliant manner for larger structs. 3079 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 3080 int Size = Ins[i].Flags.getByValSize(); 3081 unsigned NumRegs = (Size + 7) / 8; 3082 3083 // FIXME: This works on big-endian for composite byvals, which are the common 3084 // case. It should also work for fundamental types too. 3085 unsigned FrameIdx = 3086 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false); 3087 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT); 3088 InVals.push_back(FrameIdxN); 3089 3090 continue; 3091 } 3092 3093 if (VA.isRegLoc()) { 3094 // Arguments stored in registers. 3095 EVT RegVT = VA.getLocVT(); 3096 3097 SDValue ArgValue; 3098 const TargetRegisterClass *RC; 3099 3100 if (RegVT == MVT::i32) 3101 RC = &AArch64::GPR32RegClass; 3102 else if (RegVT == MVT::i64) 3103 RC = &AArch64::GPR64RegClass; 3104 else if (RegVT == MVT::f16) 3105 RC = &AArch64::FPR16RegClass; 3106 else if (RegVT == MVT::f32) 3107 RC = &AArch64::FPR32RegClass; 3108 else if (RegVT == MVT::f64 || RegVT.is64BitVector()) 3109 RC = &AArch64::FPR64RegClass; 3110 else if (RegVT == MVT::f128 || RegVT.is128BitVector()) 3111 RC = &AArch64::FPR128RegClass; 3112 else 3113 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering"); 3114 3115 // Transform the arguments in physical registers into virtual ones. 3116 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC); 3117 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT); 3118 3119 // If this is an 8, 16 or 32-bit value, it is really passed promoted 3120 // to 64 bits. Insert an assert[sz]ext to capture this, then 3121 // truncate to the right size. 3122 switch (VA.getLocInfo()) { 3123 default: 3124 llvm_unreachable("Unknown loc info!"); 3125 case CCValAssign::Full: 3126 break; 3127 case CCValAssign::BCvt: 3128 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue); 3129 break; 3130 case CCValAssign::AExt: 3131 case CCValAssign::SExt: 3132 case CCValAssign::ZExt: 3133 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt 3134 // nodes after our lowering. 3135 assert(RegVT == Ins[i].VT && "incorrect register location selected"); 3136 break; 3137 } 3138 3139 InVals.push_back(ArgValue); 3140 3141 } else { // VA.isRegLoc() 3142 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem"); 3143 unsigned ArgOffset = VA.getLocMemOffset(); 3144 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8; 3145 3146 uint32_t BEAlign = 0; 3147 if (!Subtarget->isLittleEndian() && ArgSize < 8 && 3148 !Ins[i].Flags.isInConsecutiveRegs()) 3149 BEAlign = 8 - ArgSize; 3150 3151 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true); 3152 3153 // Create load nodes to retrieve arguments from the stack. 3154 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 3155 SDValue ArgValue; 3156 3157 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT) 3158 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD; 3159 MVT MemVT = VA.getValVT(); 3160 3161 switch (VA.getLocInfo()) { 3162 default: 3163 break; 3164 case CCValAssign::BCvt: 3165 MemVT = VA.getLocVT(); 3166 break; 3167 case CCValAssign::SExt: 3168 ExtType = ISD::SEXTLOAD; 3169 break; 3170 case CCValAssign::ZExt: 3171 ExtType = ISD::ZEXTLOAD; 3172 break; 3173 case CCValAssign::AExt: 3174 ExtType = ISD::EXTLOAD; 3175 break; 3176 } 3177 3178 ArgValue = DAG.getExtLoad( 3179 ExtType, DL, VA.getLocVT(), Chain, FIN, 3180 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), 3181 MemVT); 3182 3183 InVals.push_back(ArgValue); 3184 } 3185 } 3186 3187 // varargs 3188 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 3189 if (isVarArg) { 3190 if (!Subtarget->isTargetDarwin() || IsWin64) { 3191 // The AAPCS variadic function ABI is identical to the non-variadic 3192 // one. As a result there may be more arguments in registers and we should 3193 // save them for future reference. 3194 // Win64 variadic functions also pass arguments in registers, but all float 3195 // arguments are passed in integer registers. 3196 saveVarArgRegisters(CCInfo, DAG, DL, Chain); 3197 } 3198 3199 // This will point to the next argument passed via stack. 3200 unsigned StackOffset = CCInfo.getNextStackOffset(); 3201 // We currently pass all varargs at 8-byte alignment. 3202 StackOffset = ((StackOffset + 7) & ~7); 3203 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true)); 3204 3205 if (MFI.hasMustTailInVarArgFunc()) { 3206 SmallVector<MVT, 2> RegParmTypes; 3207 RegParmTypes.push_back(MVT::i64); 3208 RegParmTypes.push_back(MVT::f128); 3209 // Compute the set of forwarded registers. The rest are scratch. 3210 SmallVectorImpl<ForwardedRegister> &Forwards = 3211 FuncInfo->getForwardedMustTailRegParms(); 3212 CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, 3213 CC_AArch64_AAPCS); 3214 3215 // Conservatively forward X8, since it might be used for aggregate return. 3216 if (!CCInfo.isAllocated(AArch64::X8)) { 3217 unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass); 3218 Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64)); 3219 } 3220 } 3221 } 3222 3223 // On Windows, InReg pointers must be returned, so record the pointer in a 3224 // virtual register at the start of the function so it can be returned in the 3225 // epilogue. 3226 if (IsWin64) { 3227 for (unsigned I = 0, E = Ins.size(); I != E; ++I) { 3228 if (Ins[I].Flags.isInReg()) { 3229 assert(!FuncInfo->getSRetReturnReg()); 3230 3231 MVT PtrTy = getPointerTy(DAG.getDataLayout()); 3232 unsigned Reg = 3233 MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy)); 3234 FuncInfo->setSRetReturnReg(Reg); 3235 3236 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]); 3237 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain); 3238 break; 3239 } 3240 } 3241 } 3242 3243 unsigned StackArgSize = CCInfo.getNextStackOffset(); 3244 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3245 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) { 3246 // This is a non-standard ABI so by fiat I say we're allowed to make full 3247 // use of the stack area to be popped, which must be aligned to 16 bytes in 3248 // any case: 3249 StackArgSize = alignTo(StackArgSize, 16); 3250 3251 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding 3252 // a multiple of 16. 3253 FuncInfo->setArgumentStackToRestore(StackArgSize); 3254 3255 // This realignment carries over to the available bytes below. Our own 3256 // callers will guarantee the space is free by giving an aligned value to 3257 // CALLSEQ_START. 3258 } 3259 // Even if we're not expected to free up the space, it's useful to know how 3260 // much is there while considering tail calls (because we can reuse it). 3261 FuncInfo->setBytesInStackArgArea(StackArgSize); 3262 3263 if (Subtarget->hasCustomCallingConv()) 3264 Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF); 3265 3266 return Chain; 3267 } 3268 3269 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo, 3270 SelectionDAG &DAG, 3271 const SDLoc &DL, 3272 SDValue &Chain) const { 3273 MachineFunction &MF = DAG.getMachineFunction(); 3274 MachineFrameInfo &MFI = MF.getFrameInfo(); 3275 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 3276 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3277 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()); 3278 3279 SmallVector<SDValue, 8> MemOps; 3280 3281 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2, 3282 AArch64::X3, AArch64::X4, AArch64::X5, 3283 AArch64::X6, AArch64::X7 }; 3284 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs); 3285 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs); 3286 3287 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR); 3288 int GPRIdx = 0; 3289 if (GPRSaveSize != 0) { 3290 if (IsWin64) { 3291 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false); 3292 if (GPRSaveSize & 15) 3293 // The extra size here, if triggered, will always be 8. 3294 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false); 3295 } else 3296 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false); 3297 3298 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT); 3299 3300 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) { 3301 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass); 3302 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64); 3303 SDValue Store = DAG.getStore( 3304 Val.getValue(1), DL, Val, FIN, 3305 IsWin64 3306 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), 3307 GPRIdx, 3308 (i - FirstVariadicGPR) * 8) 3309 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8)); 3310 MemOps.push_back(Store); 3311 FIN = 3312 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT)); 3313 } 3314 } 3315 FuncInfo->setVarArgsGPRIndex(GPRIdx); 3316 FuncInfo->setVarArgsGPRSize(GPRSaveSize); 3317 3318 if (Subtarget->hasFPARMv8() && !IsWin64) { 3319 static const MCPhysReg FPRArgRegs[] = { 3320 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, 3321 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7}; 3322 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs); 3323 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs); 3324 3325 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR); 3326 int FPRIdx = 0; 3327 if (FPRSaveSize != 0) { 3328 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false); 3329 3330 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT); 3331 3332 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) { 3333 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass); 3334 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128); 3335 3336 SDValue Store = DAG.getStore( 3337 Val.getValue(1), DL, Val, FIN, 3338 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16)); 3339 MemOps.push_back(Store); 3340 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, 3341 DAG.getConstant(16, DL, PtrVT)); 3342 } 3343 } 3344 FuncInfo->setVarArgsFPRIndex(FPRIdx); 3345 FuncInfo->setVarArgsFPRSize(FPRSaveSize); 3346 } 3347 3348 if (!MemOps.empty()) { 3349 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 3350 } 3351 } 3352 3353 /// LowerCallResult - Lower the result values of a call into the 3354 /// appropriate copies out of appropriate physical registers. 3355 SDValue AArch64TargetLowering::LowerCallResult( 3356 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg, 3357 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 3358 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn, 3359 SDValue ThisVal) const { 3360 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 3361 ? RetCC_AArch64_WebKit_JS 3362 : RetCC_AArch64_AAPCS; 3363 // Assign locations to each value returned by this call. 3364 SmallVector<CCValAssign, 16> RVLocs; 3365 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 3366 *DAG.getContext()); 3367 CCInfo.AnalyzeCallResult(Ins, RetCC); 3368 3369 // Copy all of the result registers out of their specified physreg. 3370 for (unsigned i = 0; i != RVLocs.size(); ++i) { 3371 CCValAssign VA = RVLocs[i]; 3372 3373 // Pass 'this' value directly from the argument to return value, to avoid 3374 // reg unit interference 3375 if (i == 0 && isThisReturn) { 3376 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 && 3377 "unexpected return calling convention register assignment"); 3378 InVals.push_back(ThisVal); 3379 continue; 3380 } 3381 3382 SDValue Val = 3383 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag); 3384 Chain = Val.getValue(1); 3385 InFlag = Val.getValue(2); 3386 3387 switch (VA.getLocInfo()) { 3388 default: 3389 llvm_unreachable("Unknown loc info!"); 3390 case CCValAssign::Full: 3391 break; 3392 case CCValAssign::BCvt: 3393 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 3394 break; 3395 } 3396 3397 InVals.push_back(Val); 3398 } 3399 3400 return Chain; 3401 } 3402 3403 /// Return true if the calling convention is one that we can guarantee TCO for. 3404 static bool canGuaranteeTCO(CallingConv::ID CC) { 3405 return CC == CallingConv::Fast; 3406 } 3407 3408 /// Return true if we might ever do TCO for calls with this calling convention. 3409 static bool mayTailCallThisCC(CallingConv::ID CC) { 3410 switch (CC) { 3411 case CallingConv::C: 3412 case CallingConv::PreserveMost: 3413 case CallingConv::Swift: 3414 return true; 3415 default: 3416 return canGuaranteeTCO(CC); 3417 } 3418 } 3419 3420 bool AArch64TargetLowering::isEligibleForTailCallOptimization( 3421 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg, 3422 const SmallVectorImpl<ISD::OutputArg> &Outs, 3423 const SmallVectorImpl<SDValue> &OutVals, 3424 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const { 3425 if (!mayTailCallThisCC(CalleeCC)) 3426 return false; 3427 3428 MachineFunction &MF = DAG.getMachineFunction(); 3429 const Function &CallerF = MF.getFunction(); 3430 CallingConv::ID CallerCC = CallerF.getCallingConv(); 3431 bool CCMatch = CallerCC == CalleeCC; 3432 3433 // Byval parameters hand the function a pointer directly into the stack area 3434 // we want to reuse during a tail call. Working around this *is* possible (see 3435 // X86) but less efficient and uglier in LowerCall. 3436 for (Function::const_arg_iterator i = CallerF.arg_begin(), 3437 e = CallerF.arg_end(); 3438 i != e; ++i) { 3439 if (i->hasByValAttr()) 3440 return false; 3441 3442 // On Windows, "inreg" attributes signify non-aggregate indirect returns. 3443 // In this case, it is necessary to save/restore X0 in the callee. Tail 3444 // call opt interferes with this. So we disable tail call opt when the 3445 // caller has an argument with "inreg" attribute. 3446 3447 // FIXME: Check whether the callee also has an "inreg" argument. 3448 if (i->hasInRegAttr()) 3449 return false; 3450 } 3451 3452 if (getTargetMachine().Options.GuaranteedTailCallOpt) 3453 return canGuaranteeTCO(CalleeCC) && CCMatch; 3454 3455 // Externally-defined functions with weak linkage should not be 3456 // tail-called on AArch64 when the OS does not support dynamic 3457 // pre-emption of symbols, as the AAELF spec requires normal calls 3458 // to undefined weak functions to be replaced with a NOP or jump to the 3459 // next instruction. The behaviour of branch instructions in this 3460 // situation (as used for tail calls) is implementation-defined, so we 3461 // cannot rely on the linker replacing the tail call with a return. 3462 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3463 const GlobalValue *GV = G->getGlobal(); 3464 const Triple &TT = getTargetMachine().getTargetTriple(); 3465 if (GV->hasExternalWeakLinkage() && 3466 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO())) 3467 return false; 3468 } 3469 3470 // Now we search for cases where we can use a tail call without changing the 3471 // ABI. Sibcall is used in some places (particularly gcc) to refer to this 3472 // concept. 3473 3474 // I want anyone implementing a new calling convention to think long and hard 3475 // about this assert. 3476 assert((!isVarArg || CalleeCC == CallingConv::C) && 3477 "Unexpected variadic calling convention"); 3478 3479 LLVMContext &C = *DAG.getContext(); 3480 if (isVarArg && !Outs.empty()) { 3481 // At least two cases here: if caller is fastcc then we can't have any 3482 // memory arguments (we'd be expected to clean up the stack afterwards). If 3483 // caller is C then we could potentially use its argument area. 3484 3485 // FIXME: for now we take the most conservative of these in both cases: 3486 // disallow all variadic memory operands. 3487 SmallVector<CCValAssign, 16> ArgLocs; 3488 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 3489 3490 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true)); 3491 for (const CCValAssign &ArgLoc : ArgLocs) 3492 if (!ArgLoc.isRegLoc()) 3493 return false; 3494 } 3495 3496 // Check that the call results are passed in the same way. 3497 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins, 3498 CCAssignFnForCall(CalleeCC, isVarArg), 3499 CCAssignFnForCall(CallerCC, isVarArg))) 3500 return false; 3501 // The callee has to preserve all registers the caller needs to preserve. 3502 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 3503 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 3504 if (!CCMatch) { 3505 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 3506 if (Subtarget->hasCustomCallingConv()) { 3507 TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved); 3508 TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved); 3509 } 3510 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 3511 return false; 3512 } 3513 3514 // Nothing more to check if the callee is taking no arguments 3515 if (Outs.empty()) 3516 return true; 3517 3518 SmallVector<CCValAssign, 16> ArgLocs; 3519 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C); 3520 3521 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg)); 3522 3523 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 3524 3525 // If the stack arguments for this call do not fit into our own save area then 3526 // the call cannot be made tail. 3527 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea()) 3528 return false; 3529 3530 const MachineRegisterInfo &MRI = MF.getRegInfo(); 3531 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals)) 3532 return false; 3533 3534 return true; 3535 } 3536 3537 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain, 3538 SelectionDAG &DAG, 3539 MachineFrameInfo &MFI, 3540 int ClobberedFI) const { 3541 SmallVector<SDValue, 8> ArgChains; 3542 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI); 3543 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1; 3544 3545 // Include the original chain at the beginning of the list. When this is 3546 // used by target LowerCall hooks, this helps legalize find the 3547 // CALLSEQ_BEGIN node. 3548 ArgChains.push_back(Chain); 3549 3550 // Add a chain value for each stack argument corresponding 3551 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(), 3552 UE = DAG.getEntryNode().getNode()->use_end(); 3553 U != UE; ++U) 3554 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U)) 3555 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr())) 3556 if (FI->getIndex() < 0) { 3557 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex()); 3558 int64_t InLastByte = InFirstByte; 3559 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1; 3560 3561 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) || 3562 (FirstByte <= InFirstByte && InFirstByte <= LastByte)) 3563 ArgChains.push_back(SDValue(L, 1)); 3564 } 3565 3566 // Build a tokenfactor for all the chains. 3567 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains); 3568 } 3569 3570 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC, 3571 bool TailCallOpt) const { 3572 return CallCC == CallingConv::Fast && TailCallOpt; 3573 } 3574 3575 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain, 3576 /// and add input and output parameter nodes. 3577 SDValue 3578 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI, 3579 SmallVectorImpl<SDValue> &InVals) const { 3580 SelectionDAG &DAG = CLI.DAG; 3581 SDLoc &DL = CLI.DL; 3582 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs; 3583 SmallVector<SDValue, 32> &OutVals = CLI.OutVals; 3584 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins; 3585 SDValue Chain = CLI.Chain; 3586 SDValue Callee = CLI.Callee; 3587 bool &IsTailCall = CLI.IsTailCall; 3588 CallingConv::ID CallConv = CLI.CallConv; 3589 bool IsVarArg = CLI.IsVarArg; 3590 3591 MachineFunction &MF = DAG.getMachineFunction(); 3592 bool IsThisReturn = false; 3593 3594 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 3595 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt; 3596 bool IsSibCall = false; 3597 3598 if (IsTailCall) { 3599 // Check if it's really possible to do a tail call. 3600 IsTailCall = isEligibleForTailCallOptimization( 3601 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG); 3602 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) 3603 report_fatal_error("failed to perform tail call elimination on a call " 3604 "site marked musttail"); 3605 3606 // A sibling call is one where we're under the usual C ABI and not planning 3607 // to change that but can still do a tail call: 3608 if (!TailCallOpt && IsTailCall) 3609 IsSibCall = true; 3610 3611 if (IsTailCall) 3612 ++NumTailCalls; 3613 } 3614 3615 // Analyze operands of the call, assigning locations to each operand. 3616 SmallVector<CCValAssign, 16> ArgLocs; 3617 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, 3618 *DAG.getContext()); 3619 3620 if (IsVarArg) { 3621 // Handle fixed and variable vector arguments differently. 3622 // Variable vector arguments always go into memory. 3623 unsigned NumArgs = Outs.size(); 3624 3625 for (unsigned i = 0; i != NumArgs; ++i) { 3626 MVT ArgVT = Outs[i].VT; 3627 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 3628 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, 3629 /*IsVarArg=*/ !Outs[i].IsFixed); 3630 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo); 3631 assert(!Res && "Call operand has unhandled type"); 3632 (void)Res; 3633 } 3634 } else { 3635 // At this point, Outs[].VT may already be promoted to i32. To correctly 3636 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and 3637 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT. 3638 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here 3639 // we use a special version of AnalyzeCallOperands to pass in ValVT and 3640 // LocVT. 3641 unsigned NumArgs = Outs.size(); 3642 for (unsigned i = 0; i != NumArgs; ++i) { 3643 MVT ValVT = Outs[i].VT; 3644 // Get type of the original argument. 3645 EVT ActualVT = getValueType(DAG.getDataLayout(), 3646 CLI.getArgs()[Outs[i].OrigArgIndex].Ty, 3647 /*AllowUnknown*/ true); 3648 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT; 3649 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 3650 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16. 3651 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8) 3652 ValVT = MVT::i8; 3653 else if (ActualMVT == MVT::i16) 3654 ValVT = MVT::i16; 3655 3656 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false); 3657 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo); 3658 assert(!Res && "Call operand has unhandled type"); 3659 (void)Res; 3660 } 3661 } 3662 3663 // Get a count of how many bytes are to be pushed on the stack. 3664 unsigned NumBytes = CCInfo.getNextStackOffset(); 3665 3666 if (IsSibCall) { 3667 // Since we're not changing the ABI to make this a tail call, the memory 3668 // operands are already available in the caller's incoming argument space. 3669 NumBytes = 0; 3670 } 3671 3672 // FPDiff is the byte offset of the call's argument area from the callee's. 3673 // Stores to callee stack arguments will be placed in FixedStackSlots offset 3674 // by this amount for a tail call. In a sibling call it must be 0 because the 3675 // caller will deallocate the entire stack and the callee still expects its 3676 // arguments to begin at SP+0. Completely unused for non-tail calls. 3677 int FPDiff = 0; 3678 3679 if (IsTailCall && !IsSibCall) { 3680 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea(); 3681 3682 // Since callee will pop argument stack as a tail call, we must keep the 3683 // popped size 16-byte aligned. 3684 NumBytes = alignTo(NumBytes, 16); 3685 3686 // FPDiff will be negative if this tail call requires more space than we 3687 // would automatically have in our incoming argument space. Positive if we 3688 // can actually shrink the stack. 3689 FPDiff = NumReusableBytes - NumBytes; 3690 3691 // The stack pointer must be 16-byte aligned at all times it's used for a 3692 // memory operation, which in practice means at *all* times and in 3693 // particular across call boundaries. Therefore our own arguments started at 3694 // a 16-byte aligned SP and the delta applied for the tail call should 3695 // satisfy the same constraint. 3696 assert(FPDiff % 16 == 0 && "unaligned stack on tail call"); 3697 } 3698 3699 // Adjust the stack pointer for the new arguments... 3700 // These operations are automatically eliminated by the prolog/epilog pass 3701 if (!IsSibCall) 3702 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL); 3703 3704 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP, 3705 getPointerTy(DAG.getDataLayout())); 3706 3707 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass; 3708 SmallVector<SDValue, 8> MemOpChains; 3709 auto PtrVT = getPointerTy(DAG.getDataLayout()); 3710 3711 if (IsVarArg && CLI.CS && CLI.CS.isMustTailCall()) { 3712 const auto &Forwards = FuncInfo->getForwardedMustTailRegParms(); 3713 for (const auto &F : Forwards) { 3714 SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT); 3715 RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val)); 3716 } 3717 } 3718 3719 // Walk the register/memloc assignments, inserting copies/loads. 3720 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e; 3721 ++i, ++realArgIdx) { 3722 CCValAssign &VA = ArgLocs[i]; 3723 SDValue Arg = OutVals[realArgIdx]; 3724 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags; 3725 3726 // Promote the value if needed. 3727 switch (VA.getLocInfo()) { 3728 default: 3729 llvm_unreachable("Unknown loc info!"); 3730 case CCValAssign::Full: 3731 break; 3732 case CCValAssign::SExt: 3733 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg); 3734 break; 3735 case CCValAssign::ZExt: 3736 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3737 break; 3738 case CCValAssign::AExt: 3739 if (Outs[realArgIdx].ArgVT == MVT::i1) { 3740 // AAPCS requires i1 to be zero-extended to 8-bits by the caller. 3741 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 3742 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg); 3743 } 3744 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg); 3745 break; 3746 case CCValAssign::BCvt: 3747 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 3748 break; 3749 case CCValAssign::FPExt: 3750 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg); 3751 break; 3752 } 3753 3754 if (VA.isRegLoc()) { 3755 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() && 3756 Outs[0].VT == MVT::i64) { 3757 assert(VA.getLocVT() == MVT::i64 && 3758 "unexpected calling convention register assignment"); 3759 assert(!Ins.empty() && Ins[0].VT == MVT::i64 && 3760 "unexpected use of 'returned'"); 3761 IsThisReturn = true; 3762 } 3763 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg)); 3764 } else { 3765 assert(VA.isMemLoc()); 3766 3767 SDValue DstAddr; 3768 MachinePointerInfo DstInfo; 3769 3770 // FIXME: This works on big-endian for composite byvals, which are the 3771 // common case. It should also work for fundamental types too. 3772 uint32_t BEAlign = 0; 3773 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8 3774 : VA.getValVT().getSizeInBits(); 3775 OpSize = (OpSize + 7) / 8; 3776 if (!Subtarget->isLittleEndian() && !Flags.isByVal() && 3777 !Flags.isInConsecutiveRegs()) { 3778 if (OpSize < 8) 3779 BEAlign = 8 - OpSize; 3780 } 3781 unsigned LocMemOffset = VA.getLocMemOffset(); 3782 int32_t Offset = LocMemOffset + BEAlign; 3783 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 3784 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 3785 3786 if (IsTailCall) { 3787 Offset = Offset + FPDiff; 3788 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true); 3789 3790 DstAddr = DAG.getFrameIndex(FI, PtrVT); 3791 DstInfo = 3792 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI); 3793 3794 // Make sure any stack arguments overlapping with where we're storing 3795 // are loaded before this eventual operation. Otherwise they'll be 3796 // clobbered. 3797 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI); 3798 } else { 3799 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL); 3800 3801 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff); 3802 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(), 3803 LocMemOffset); 3804 } 3805 3806 if (Outs[i].Flags.isByVal()) { 3807 SDValue SizeNode = 3808 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64); 3809 SDValue Cpy = DAG.getMemcpy( 3810 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(), 3811 /*isVol = */ false, /*AlwaysInline = */ false, 3812 /*isTailCall = */ false, 3813 DstInfo, MachinePointerInfo()); 3814 3815 MemOpChains.push_back(Cpy); 3816 } else { 3817 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already 3818 // promoted to a legal register type i32, we should truncate Arg back to 3819 // i1/i8/i16. 3820 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 || 3821 VA.getValVT() == MVT::i16) 3822 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg); 3823 3824 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo); 3825 MemOpChains.push_back(Store); 3826 } 3827 } 3828 } 3829 3830 if (!MemOpChains.empty()) 3831 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 3832 3833 // Build a sequence of copy-to-reg nodes chained together with token chain 3834 // and flag operands which copy the outgoing args into the appropriate regs. 3835 SDValue InFlag; 3836 for (auto &RegToPass : RegsToPass) { 3837 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first, 3838 RegToPass.second, InFlag); 3839 InFlag = Chain.getValue(1); 3840 } 3841 3842 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every 3843 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol 3844 // node so that legalize doesn't hack it. 3845 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 3846 auto GV = G->getGlobal(); 3847 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) == 3848 AArch64II::MO_GOT) { 3849 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT); 3850 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 3851 } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) { 3852 assert(Subtarget->isTargetWindows() && 3853 "Windows is the only supported COFF target"); 3854 Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT); 3855 } else { 3856 const GlobalValue *GV = G->getGlobal(); 3857 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0); 3858 } 3859 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 3860 if (getTargetMachine().getCodeModel() == CodeModel::Large && 3861 Subtarget->isTargetMachO()) { 3862 const char *Sym = S->getSymbol(); 3863 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT); 3864 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee); 3865 } else { 3866 const char *Sym = S->getSymbol(); 3867 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0); 3868 } 3869 } 3870 3871 // We don't usually want to end the call-sequence here because we would tidy 3872 // the frame up *after* the call, however in the ABI-changing tail-call case 3873 // we've carefully laid out the parameters so that when sp is reset they'll be 3874 // in the correct location. 3875 if (IsTailCall && !IsSibCall) { 3876 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 3877 DAG.getIntPtrConstant(0, DL, true), InFlag, DL); 3878 InFlag = Chain.getValue(1); 3879 } 3880 3881 std::vector<SDValue> Ops; 3882 Ops.push_back(Chain); 3883 Ops.push_back(Callee); 3884 3885 if (IsTailCall) { 3886 // Each tail call may have to adjust the stack by a different amount, so 3887 // this information must travel along with the operation for eventual 3888 // consumption by emitEpilogue. 3889 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32)); 3890 } 3891 3892 // Add argument registers to the end of the list so that they are known live 3893 // into the call. 3894 for (auto &RegToPass : RegsToPass) 3895 Ops.push_back(DAG.getRegister(RegToPass.first, 3896 RegToPass.second.getValueType())); 3897 3898 // Add a register mask operand representing the call-preserved registers. 3899 const uint32_t *Mask; 3900 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 3901 if (IsThisReturn) { 3902 // For 'this' returns, use the X0-preserving mask if applicable 3903 Mask = TRI->getThisReturnPreservedMask(MF, CallConv); 3904 if (!Mask) { 3905 IsThisReturn = false; 3906 Mask = TRI->getCallPreservedMask(MF, CallConv); 3907 } 3908 } else 3909 Mask = TRI->getCallPreservedMask(MF, CallConv); 3910 3911 if (Subtarget->hasCustomCallingConv()) 3912 TRI->UpdateCustomCallPreservedMask(MF, &Mask); 3913 3914 if (TRI->isAnyArgRegReserved(MF)) 3915 TRI->emitReservedArgRegCallError(MF); 3916 3917 assert(Mask && "Missing call preserved mask for calling convention"); 3918 Ops.push_back(DAG.getRegisterMask(Mask)); 3919 3920 if (InFlag.getNode()) 3921 Ops.push_back(InFlag); 3922 3923 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 3924 3925 // If we're doing a tall call, use a TC_RETURN here rather than an 3926 // actual call instruction. 3927 if (IsTailCall) { 3928 MF.getFrameInfo().setHasTailCall(); 3929 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops); 3930 } 3931 3932 // Returns a chain and a flag for retval copy to use. 3933 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops); 3934 InFlag = Chain.getValue(1); 3935 3936 uint64_t CalleePopBytes = 3937 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0; 3938 3939 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true), 3940 DAG.getIntPtrConstant(CalleePopBytes, DL, true), 3941 InFlag, DL); 3942 if (!Ins.empty()) 3943 InFlag = Chain.getValue(1); 3944 3945 // Handle result values, copying them out of physregs into vregs that we 3946 // return. 3947 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG, 3948 InVals, IsThisReturn, 3949 IsThisReturn ? OutVals[0] : SDValue()); 3950 } 3951 3952 bool AArch64TargetLowering::CanLowerReturn( 3953 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg, 3954 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 3955 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 3956 ? RetCC_AArch64_WebKit_JS 3957 : RetCC_AArch64_AAPCS; 3958 SmallVector<CCValAssign, 16> RVLocs; 3959 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context); 3960 return CCInfo.CheckReturn(Outs, RetCC); 3961 } 3962 3963 SDValue 3964 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 3965 bool isVarArg, 3966 const SmallVectorImpl<ISD::OutputArg> &Outs, 3967 const SmallVectorImpl<SDValue> &OutVals, 3968 const SDLoc &DL, SelectionDAG &DAG) const { 3969 auto &MF = DAG.getMachineFunction(); 3970 auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 3971 3972 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS 3973 ? RetCC_AArch64_WebKit_JS 3974 : RetCC_AArch64_AAPCS; 3975 SmallVector<CCValAssign, 16> RVLocs; 3976 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs, 3977 *DAG.getContext()); 3978 CCInfo.AnalyzeReturn(Outs, RetCC); 3979 3980 // Copy the result values into the output registers. 3981 SDValue Flag; 3982 SmallVector<SDValue, 4> RetOps(1, Chain); 3983 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size(); 3984 ++i, ++realRVLocIdx) { 3985 CCValAssign &VA = RVLocs[i]; 3986 assert(VA.isRegLoc() && "Can only return in registers!"); 3987 SDValue Arg = OutVals[realRVLocIdx]; 3988 3989 switch (VA.getLocInfo()) { 3990 default: 3991 llvm_unreachable("Unknown loc info!"); 3992 case CCValAssign::Full: 3993 if (Outs[i].ArgVT == MVT::i1) { 3994 // AAPCS requires i1 to be zero-extended to i8 by the producer of the 3995 // value. This is strictly redundant on Darwin (which uses "zeroext 3996 // i1"), but will be optimised out before ISel. 3997 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg); 3998 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg); 3999 } 4000 break; 4001 case CCValAssign::BCvt: 4002 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg); 4003 break; 4004 } 4005 4006 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag); 4007 Flag = Chain.getValue(1); 4008 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 4009 } 4010 4011 // Windows AArch64 ABIs require that for returning structs by value we copy 4012 // the sret argument into X0 for the return. 4013 // We saved the argument into a virtual register in the entry block, 4014 // so now we copy the value out and into X0. 4015 if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) { 4016 SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg, 4017 getPointerTy(MF.getDataLayout())); 4018 4019 unsigned RetValReg = AArch64::X0; 4020 Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag); 4021 Flag = Chain.getValue(1); 4022 4023 RetOps.push_back( 4024 DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout()))); 4025 } 4026 4027 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 4028 const MCPhysReg *I = 4029 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction()); 4030 if (I) { 4031 for (; *I; ++I) { 4032 if (AArch64::GPR64RegClass.contains(*I)) 4033 RetOps.push_back(DAG.getRegister(*I, MVT::i64)); 4034 else if (AArch64::FPR64RegClass.contains(*I)) 4035 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64))); 4036 else 4037 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 4038 } 4039 } 4040 4041 RetOps[0] = Chain; // Update chain. 4042 4043 // Add the flag if we have it. 4044 if (Flag.getNode()) 4045 RetOps.push_back(Flag); 4046 4047 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps); 4048 } 4049 4050 //===----------------------------------------------------------------------===// 4051 // Other Lowering Code 4052 //===----------------------------------------------------------------------===// 4053 4054 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty, 4055 SelectionDAG &DAG, 4056 unsigned Flag) const { 4057 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 4058 N->getOffset(), Flag); 4059 } 4060 4061 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty, 4062 SelectionDAG &DAG, 4063 unsigned Flag) const { 4064 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag); 4065 } 4066 4067 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty, 4068 SelectionDAG &DAG, 4069 unsigned Flag) const { 4070 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(), 4071 N->getOffset(), Flag); 4072 } 4073 4074 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty, 4075 SelectionDAG &DAG, 4076 unsigned Flag) const { 4077 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag); 4078 } 4079 4080 // (loadGOT sym) 4081 template <class NodeTy> 4082 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG, 4083 unsigned Flags) const { 4084 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n"); 4085 SDLoc DL(N); 4086 EVT Ty = getPointerTy(DAG.getDataLayout()); 4087 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags); 4088 // FIXME: Once remat is capable of dealing with instructions with register 4089 // operands, expand this into two nodes instead of using a wrapper node. 4090 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr); 4091 } 4092 4093 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym)) 4094 template <class NodeTy> 4095 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG, 4096 unsigned Flags) const { 4097 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n"); 4098 SDLoc DL(N); 4099 EVT Ty = getPointerTy(DAG.getDataLayout()); 4100 const unsigned char MO_NC = AArch64II::MO_NC; 4101 return DAG.getNode( 4102 AArch64ISD::WrapperLarge, DL, Ty, 4103 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags), 4104 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags), 4105 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags), 4106 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags)); 4107 } 4108 4109 // (addlow (adrp %hi(sym)) %lo(sym)) 4110 template <class NodeTy> 4111 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 4112 unsigned Flags) const { 4113 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n"); 4114 SDLoc DL(N); 4115 EVT Ty = getPointerTy(DAG.getDataLayout()); 4116 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags); 4117 SDValue Lo = getTargetNode(N, Ty, DAG, 4118 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags); 4119 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi); 4120 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo); 4121 } 4122 4123 // (adr sym) 4124 template <class NodeTy> 4125 SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG, 4126 unsigned Flags) const { 4127 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n"); 4128 SDLoc DL(N); 4129 EVT Ty = getPointerTy(DAG.getDataLayout()); 4130 SDValue Sym = getTargetNode(N, Ty, DAG, Flags); 4131 return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym); 4132 } 4133 4134 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op, 4135 SelectionDAG &DAG) const { 4136 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op); 4137 const GlobalValue *GV = GN->getGlobal(); 4138 unsigned char OpFlags = 4139 Subtarget->ClassifyGlobalReference(GV, getTargetMachine()); 4140 4141 if (OpFlags != AArch64II::MO_NO_FLAG) 4142 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 && 4143 "unexpected offset in global node"); 4144 4145 // This also catches the large code model case for Darwin, and tiny code 4146 // model with got relocations. 4147 if ((OpFlags & AArch64II::MO_GOT) != 0) { 4148 return getGOT(GN, DAG, OpFlags); 4149 } 4150 4151 SDValue Result; 4152 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 4153 Result = getAddrLarge(GN, DAG, OpFlags); 4154 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 4155 Result = getAddrTiny(GN, DAG, OpFlags); 4156 } else { 4157 Result = getAddr(GN, DAG, OpFlags); 4158 } 4159 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4160 SDLoc DL(GN); 4161 if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB)) 4162 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result, 4163 MachinePointerInfo::getGOT(DAG.getMachineFunction())); 4164 return Result; 4165 } 4166 4167 /// Convert a TLS address reference into the correct sequence of loads 4168 /// and calls to compute the variable's address (for Darwin, currently) and 4169 /// return an SDValue containing the final node. 4170 4171 /// Darwin only has one TLS scheme which must be capable of dealing with the 4172 /// fully general situation, in the worst case. This means: 4173 /// + "extern __thread" declaration. 4174 /// + Defined in a possibly unknown dynamic library. 4175 /// 4176 /// The general system is that each __thread variable has a [3 x i64] descriptor 4177 /// which contains information used by the runtime to calculate the address. The 4178 /// only part of this the compiler needs to know about is the first xword, which 4179 /// contains a function pointer that must be called with the address of the 4180 /// entire descriptor in "x0". 4181 /// 4182 /// Since this descriptor may be in a different unit, in general even the 4183 /// descriptor must be accessed via an indirect load. The "ideal" code sequence 4184 /// is: 4185 /// adrp x0, _var@TLVPPAGE 4186 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor 4187 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor, 4188 /// ; the function pointer 4189 /// blr x1 ; Uses descriptor address in x0 4190 /// ; Address of _var is now in x0. 4191 /// 4192 /// If the address of _var's descriptor *is* known to the linker, then it can 4193 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for 4194 /// a slight efficiency gain. 4195 SDValue 4196 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op, 4197 SelectionDAG &DAG) const { 4198 assert(Subtarget->isTargetDarwin() && 4199 "This function expects a Darwin target"); 4200 4201 SDLoc DL(Op); 4202 MVT PtrVT = getPointerTy(DAG.getDataLayout()); 4203 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal(); 4204 4205 SDValue TLVPAddr = 4206 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 4207 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr); 4208 4209 // The first entry in the descriptor is a function pointer that we must call 4210 // to obtain the address of the variable. 4211 SDValue Chain = DAG.getEntryNode(); 4212 SDValue FuncTLVGet = DAG.getLoad( 4213 MVT::i64, DL, Chain, DescAddr, 4214 MachinePointerInfo::getGOT(DAG.getMachineFunction()), 4215 /* Alignment = */ 8, 4216 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant | 4217 MachineMemOperand::MODereferenceable); 4218 Chain = FuncTLVGet.getValue(1); 4219 4220 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 4221 MFI.setAdjustsStack(true); 4222 4223 // TLS calls preserve all registers except those that absolutely must be 4224 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be 4225 // silly). 4226 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 4227 const uint32_t *Mask = TRI->getTLSCallPreservedMask(); 4228 if (Subtarget->hasCustomCallingConv()) 4229 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask); 4230 4231 // Finally, we can make the call. This is just a degenerate version of a 4232 // normal AArch64 call node: x0 takes the address of the descriptor, and 4233 // returns the address of the variable in this thread. 4234 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue()); 4235 Chain = 4236 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue), 4237 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64), 4238 DAG.getRegisterMask(Mask), Chain.getValue(1)); 4239 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1)); 4240 } 4241 4242 /// When accessing thread-local variables under either the general-dynamic or 4243 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will 4244 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry 4245 /// is a function pointer to carry out the resolution. 4246 /// 4247 /// The sequence is: 4248 /// adrp x0, :tlsdesc:var 4249 /// ldr x1, [x0, #:tlsdesc_lo12:var] 4250 /// add x0, x0, #:tlsdesc_lo12:var 4251 /// .tlsdesccall var 4252 /// blr x1 4253 /// (TPIDR_EL0 offset now in x0) 4254 /// 4255 /// The above sequence must be produced unscheduled, to enable the linker to 4256 /// optimize/relax this sequence. 4257 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the 4258 /// above sequence, and expanded really late in the compilation flow, to ensure 4259 /// the sequence is produced as per above. 4260 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, 4261 const SDLoc &DL, 4262 SelectionDAG &DAG) const { 4263 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4264 4265 SDValue Chain = DAG.getEntryNode(); 4266 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 4267 4268 Chain = 4269 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr}); 4270 SDValue Glue = Chain.getValue(1); 4271 4272 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue); 4273 } 4274 4275 SDValue 4276 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op, 4277 SelectionDAG &DAG) const { 4278 assert(Subtarget->isTargetELF() && "This function expects an ELF target"); 4279 if (getTargetMachine().getCodeModel() == CodeModel::Large) 4280 report_fatal_error("ELF TLS only supported in small memory model"); 4281 // Different choices can be made for the maximum size of the TLS area for a 4282 // module. For the small address model, the default TLS size is 16MiB and the 4283 // maximum TLS size is 4GiB. 4284 // FIXME: add -mtls-size command line option and make it control the 16MiB 4285 // vs. 4GiB code sequence generation. 4286 // FIXME: add tiny codemodel support. We currently generate the same code as 4287 // small, which may be larger than needed. 4288 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 4289 4290 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal()); 4291 4292 if (!EnableAArch64ELFLocalDynamicTLSGeneration) { 4293 if (Model == TLSModel::LocalDynamic) 4294 Model = TLSModel::GeneralDynamic; 4295 } 4296 4297 SDValue TPOff; 4298 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4299 SDLoc DL(Op); 4300 const GlobalValue *GV = GA->getGlobal(); 4301 4302 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT); 4303 4304 if (Model == TLSModel::LocalExec) { 4305 SDValue HiVar = DAG.getTargetGlobalAddress( 4306 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 4307 SDValue LoVar = DAG.getTargetGlobalAddress( 4308 GV, DL, PtrVT, 0, 4309 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 4310 4311 SDValue TPWithOff_lo = 4312 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase, 4313 HiVar, 4314 DAG.getTargetConstant(0, DL, MVT::i32)), 4315 0); 4316 SDValue TPWithOff = 4317 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo, 4318 LoVar, 4319 DAG.getTargetConstant(0, DL, MVT::i32)), 4320 0); 4321 return TPWithOff; 4322 } else if (Model == TLSModel::InitialExec) { 4323 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 4324 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff); 4325 } else if (Model == TLSModel::LocalDynamic) { 4326 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS 4327 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate 4328 // the beginning of the module's TLS region, followed by a DTPREL offset 4329 // calculation. 4330 4331 // These accesses will need deduplicating if there's more than one. 4332 AArch64FunctionInfo *MFI = 4333 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 4334 MFI->incNumLocalDynamicTLSAccesses(); 4335 4336 // The call needs a relocation too for linker relaxation. It doesn't make 4337 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 4338 // the address. 4339 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT, 4340 AArch64II::MO_TLS); 4341 4342 // Now we can calculate the offset from TPIDR_EL0 to this module's 4343 // thread-local area. 4344 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 4345 4346 // Now use :dtprel_whatever: operations to calculate this variable's offset 4347 // in its thread-storage area. 4348 SDValue HiVar = DAG.getTargetGlobalAddress( 4349 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 4350 SDValue LoVar = DAG.getTargetGlobalAddress( 4351 GV, DL, MVT::i64, 0, 4352 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 4353 4354 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar, 4355 DAG.getTargetConstant(0, DL, MVT::i32)), 4356 0); 4357 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar, 4358 DAG.getTargetConstant(0, DL, MVT::i32)), 4359 0); 4360 } else if (Model == TLSModel::GeneralDynamic) { 4361 // The call needs a relocation too for linker relaxation. It doesn't make 4362 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of 4363 // the address. 4364 SDValue SymAddr = 4365 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS); 4366 4367 // Finally we can make a call to calculate the offset from tpidr_el0. 4368 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG); 4369 } else 4370 llvm_unreachable("Unsupported ELF TLS access model"); 4371 4372 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff); 4373 } 4374 4375 SDValue 4376 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op, 4377 SelectionDAG &DAG) const { 4378 assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering"); 4379 4380 SDValue Chain = DAG.getEntryNode(); 4381 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4382 SDLoc DL(Op); 4383 4384 SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64); 4385 4386 // Load the ThreadLocalStoragePointer from the TEB 4387 // A pointer to the TLS array is located at offset 0x58 from the TEB. 4388 SDValue TLSArray = 4389 DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL)); 4390 TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo()); 4391 Chain = TLSArray.getValue(1); 4392 4393 // Load the TLS index from the C runtime; 4394 // This does the same as getAddr(), but without having a GlobalAddressSDNode. 4395 // This also does the same as LOADgot, but using a generic i32 load, 4396 // while LOADgot only loads i64. 4397 SDValue TLSIndexHi = 4398 DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE); 4399 SDValue TLSIndexLo = DAG.getTargetExternalSymbol( 4400 "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 4401 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi); 4402 SDValue TLSIndex = 4403 DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo); 4404 TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo()); 4405 Chain = TLSIndex.getValue(1); 4406 4407 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8 4408 // offset into the TLSArray. 4409 TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex); 4410 SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex, 4411 DAG.getConstant(3, DL, PtrVT)); 4412 SDValue TLS = DAG.getLoad(PtrVT, DL, Chain, 4413 DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot), 4414 MachinePointerInfo()); 4415 Chain = TLS.getValue(1); 4416 4417 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 4418 const GlobalValue *GV = GA->getGlobal(); 4419 SDValue TGAHi = DAG.getTargetGlobalAddress( 4420 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12); 4421 SDValue TGALo = DAG.getTargetGlobalAddress( 4422 GV, DL, PtrVT, 0, 4423 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC); 4424 4425 // Add the offset from the start of the .tls section (section base). 4426 SDValue Addr = 4427 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi, 4428 DAG.getTargetConstant(0, DL, MVT::i32)), 4429 0); 4430 Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo); 4431 return Addr; 4432 } 4433 4434 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op, 4435 SelectionDAG &DAG) const { 4436 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op); 4437 if (DAG.getTarget().useEmulatedTLS()) 4438 return LowerToTLSEmulatedModel(GA, DAG); 4439 4440 if (Subtarget->isTargetDarwin()) 4441 return LowerDarwinGlobalTLSAddress(Op, DAG); 4442 if (Subtarget->isTargetELF()) 4443 return LowerELFGlobalTLSAddress(Op, DAG); 4444 if (Subtarget->isTargetWindows()) 4445 return LowerWindowsGlobalTLSAddress(Op, DAG); 4446 4447 llvm_unreachable("Unexpected platform trying to use TLS"); 4448 } 4449 4450 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const { 4451 SDValue Chain = Op.getOperand(0); 4452 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get(); 4453 SDValue LHS = Op.getOperand(2); 4454 SDValue RHS = Op.getOperand(3); 4455 SDValue Dest = Op.getOperand(4); 4456 SDLoc dl(Op); 4457 4458 MachineFunction &MF = DAG.getMachineFunction(); 4459 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions 4460 // will not be produced, as they are conditional branch instructions that do 4461 // not set flags. 4462 bool ProduceNonFlagSettingCondBr = 4463 !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening); 4464 4465 // Handle f128 first, since lowering it will result in comparing the return 4466 // value of a libcall against zero, which is just what the rest of LowerBR_CC 4467 // is expecting to deal with. 4468 if (LHS.getValueType() == MVT::f128) { 4469 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); 4470 4471 // If softenSetCCOperands returned a scalar, we need to compare the result 4472 // against zero to select between true and false values. 4473 if (!RHS.getNode()) { 4474 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4475 CC = ISD::SETNE; 4476 } 4477 } 4478 4479 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch 4480 // instruction. 4481 if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) && 4482 (CC == ISD::SETEQ || CC == ISD::SETNE)) { 4483 // Only lower legal XALUO ops. 4484 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0))) 4485 return SDValue(); 4486 4487 // The actual operation with overflow check. 4488 AArch64CC::CondCode OFCC; 4489 SDValue Value, Overflow; 4490 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG); 4491 4492 if (CC == ISD::SETNE) 4493 OFCC = getInvertedCondCode(OFCC); 4494 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32); 4495 4496 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 4497 Overflow); 4498 } 4499 4500 if (LHS.getValueType().isInteger()) { 4501 assert((LHS.getValueType() == RHS.getValueType()) && 4502 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 4503 4504 // If the RHS of the comparison is zero, we can potentially fold this 4505 // to a specialized branch. 4506 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS); 4507 if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) { 4508 if (CC == ISD::SETEQ) { 4509 // See if we can use a TBZ to fold in an AND as well. 4510 // TBZ has a smaller branch displacement than CBZ. If the offset is 4511 // out of bounds, a late MI-layer pass rewrites branches. 4512 // 403.gcc is an example that hits this case. 4513 if (LHS.getOpcode() == ISD::AND && 4514 isa<ConstantSDNode>(LHS.getOperand(1)) && 4515 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 4516 SDValue Test = LHS.getOperand(0); 4517 uint64_t Mask = LHS.getConstantOperandVal(1); 4518 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test, 4519 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 4520 Dest); 4521 } 4522 4523 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest); 4524 } else if (CC == ISD::SETNE) { 4525 // See if we can use a TBZ to fold in an AND as well. 4526 // TBZ has a smaller branch displacement than CBZ. If the offset is 4527 // out of bounds, a late MI-layer pass rewrites branches. 4528 // 403.gcc is an example that hits this case. 4529 if (LHS.getOpcode() == ISD::AND && 4530 isa<ConstantSDNode>(LHS.getOperand(1)) && 4531 isPowerOf2_64(LHS.getConstantOperandVal(1))) { 4532 SDValue Test = LHS.getOperand(0); 4533 uint64_t Mask = LHS.getConstantOperandVal(1); 4534 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test, 4535 DAG.getConstant(Log2_64(Mask), dl, MVT::i64), 4536 Dest); 4537 } 4538 4539 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest); 4540 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) { 4541 // Don't combine AND since emitComparison converts the AND to an ANDS 4542 // (a.k.a. TST) and the test in the test bit and branch instruction 4543 // becomes redundant. This would also increase register pressure. 4544 uint64_t Mask = LHS.getValueSizeInBits() - 1; 4545 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS, 4546 DAG.getConstant(Mask, dl, MVT::i64), Dest); 4547 } 4548 } 4549 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT && 4550 LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) { 4551 // Don't combine AND since emitComparison converts the AND to an ANDS 4552 // (a.k.a. TST) and the test in the test bit and branch instruction 4553 // becomes redundant. This would also increase register pressure. 4554 uint64_t Mask = LHS.getValueSizeInBits() - 1; 4555 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS, 4556 DAG.getConstant(Mask, dl, MVT::i64), Dest); 4557 } 4558 4559 SDValue CCVal; 4560 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 4561 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal, 4562 Cmp); 4563 } 4564 4565 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 4566 LHS.getValueType() == MVT::f64); 4567 4568 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 4569 // clean. Some of them require two branches to implement. 4570 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 4571 AArch64CC::CondCode CC1, CC2; 4572 changeFPCCToAArch64CC(CC, CC1, CC2); 4573 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 4574 SDValue BR1 = 4575 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp); 4576 if (CC2 != AArch64CC::AL) { 4577 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 4578 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val, 4579 Cmp); 4580 } 4581 4582 return BR1; 4583 } 4584 4585 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op, 4586 SelectionDAG &DAG) const { 4587 EVT VT = Op.getValueType(); 4588 SDLoc DL(Op); 4589 4590 SDValue In1 = Op.getOperand(0); 4591 SDValue In2 = Op.getOperand(1); 4592 EVT SrcVT = In2.getValueType(); 4593 4594 if (SrcVT.bitsLT(VT)) 4595 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2); 4596 else if (SrcVT.bitsGT(VT)) 4597 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL)); 4598 4599 EVT VecVT; 4600 uint64_t EltMask; 4601 SDValue VecVal1, VecVal2; 4602 4603 auto setVecVal = [&] (int Idx) { 4604 if (!VT.isVector()) { 4605 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT, 4606 DAG.getUNDEF(VecVT), In1); 4607 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT, 4608 DAG.getUNDEF(VecVT), In2); 4609 } else { 4610 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1); 4611 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2); 4612 } 4613 }; 4614 4615 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) { 4616 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32); 4617 EltMask = 0x80000000ULL; 4618 setVecVal(AArch64::ssub); 4619 } else if (VT == MVT::f64 || VT == MVT::v2f64) { 4620 VecVT = MVT::v2i64; 4621 4622 // We want to materialize a mask with the high bit set, but the AdvSIMD 4623 // immediate moves cannot materialize that in a single instruction for 4624 // 64-bit elements. Instead, materialize zero and then negate it. 4625 EltMask = 0; 4626 4627 setVecVal(AArch64::dsub); 4628 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) { 4629 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16); 4630 EltMask = 0x8000ULL; 4631 setVecVal(AArch64::hsub); 4632 } else { 4633 llvm_unreachable("Invalid type for copysign!"); 4634 } 4635 4636 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT); 4637 4638 // If we couldn't materialize the mask above, then the mask vector will be 4639 // the zero vector, and we need to negate it here. 4640 if (VT == MVT::f64 || VT == MVT::v2f64) { 4641 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec); 4642 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec); 4643 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec); 4644 } 4645 4646 SDValue Sel = 4647 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec); 4648 4649 if (VT == MVT::f16) 4650 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel); 4651 if (VT == MVT::f32) 4652 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel); 4653 else if (VT == MVT::f64) 4654 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel); 4655 else 4656 return DAG.getNode(ISD::BITCAST, DL, VT, Sel); 4657 } 4658 4659 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const { 4660 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 4661 Attribute::NoImplicitFloat)) 4662 return SDValue(); 4663 4664 if (!Subtarget->hasNEON()) 4665 return SDValue(); 4666 4667 // While there is no integer popcount instruction, it can 4668 // be more efficiently lowered to the following sequence that uses 4669 // AdvSIMD registers/instructions as long as the copies to/from 4670 // the AdvSIMD registers are cheap. 4671 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd 4672 // CNT V0.8B, V0.8B // 8xbyte pop-counts 4673 // ADDV B0, V0.8B // sum 8xbyte pop-counts 4674 // UMOV X0, V0.B[0] // copy byte result back to integer reg 4675 SDValue Val = Op.getOperand(0); 4676 SDLoc DL(Op); 4677 EVT VT = Op.getValueType(); 4678 4679 if (VT == MVT::i32 || VT == MVT::i64) { 4680 if (VT == MVT::i32) 4681 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val); 4682 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val); 4683 4684 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val); 4685 SDValue UaddLV = DAG.getNode( 4686 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32, 4687 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop); 4688 4689 if (VT == MVT::i64) 4690 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV); 4691 return UaddLV; 4692 } 4693 4694 assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 || 4695 VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) && 4696 "Unexpected type for custom ctpop lowering"); 4697 4698 EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8; 4699 Val = DAG.getBitcast(VT8Bit, Val); 4700 Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val); 4701 4702 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds. 4703 unsigned EltSize = 8; 4704 unsigned NumElts = VT.is64BitVector() ? 8 : 16; 4705 while (EltSize != VT.getScalarSizeInBits()) { 4706 EltSize *= 2; 4707 NumElts /= 2; 4708 MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts); 4709 Val = DAG.getNode( 4710 ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, 4711 DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val); 4712 } 4713 4714 return Val; 4715 } 4716 4717 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const { 4718 4719 if (Op.getValueType().isVector()) 4720 return LowerVSETCC(Op, DAG); 4721 4722 SDValue LHS = Op.getOperand(0); 4723 SDValue RHS = Op.getOperand(1); 4724 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 4725 SDLoc dl(Op); 4726 4727 // We chose ZeroOrOneBooleanContents, so use zero and one. 4728 EVT VT = Op.getValueType(); 4729 SDValue TVal = DAG.getConstant(1, dl, VT); 4730 SDValue FVal = DAG.getConstant(0, dl, VT); 4731 4732 // Handle f128 first, since one possible outcome is a normal integer 4733 // comparison which gets picked up by the next if statement. 4734 if (LHS.getValueType() == MVT::f128) { 4735 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); 4736 4737 // If softenSetCCOperands returned a scalar, use it. 4738 if (!RHS.getNode()) { 4739 assert(LHS.getValueType() == Op.getValueType() && 4740 "Unexpected setcc expansion!"); 4741 return LHS; 4742 } 4743 } 4744 4745 if (LHS.getValueType().isInteger()) { 4746 SDValue CCVal; 4747 SDValue Cmp = 4748 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl); 4749 4750 // Note that we inverted the condition above, so we reverse the order of 4751 // the true and false operands here. This will allow the setcc to be 4752 // matched to a single CSINC instruction. 4753 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp); 4754 } 4755 4756 // Now we know we're dealing with FP values. 4757 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 4758 LHS.getValueType() == MVT::f64); 4759 4760 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead 4761 // and do the comparison. 4762 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 4763 4764 AArch64CC::CondCode CC1, CC2; 4765 changeFPCCToAArch64CC(CC, CC1, CC2); 4766 if (CC2 == AArch64CC::AL) { 4767 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2); 4768 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 4769 4770 // Note that we inverted the condition above, so we reverse the order of 4771 // the true and false operands here. This will allow the setcc to be 4772 // matched to a single CSINC instruction. 4773 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp); 4774 } else { 4775 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't 4776 // totally clean. Some of them require two CSELs to implement. As is in 4777 // this case, we emit the first CSEL and then emit a second using the output 4778 // of the first as the RHS. We're effectively OR'ing the two CC's together. 4779 4780 // FIXME: It would be nice if we could match the two CSELs to two CSINCs. 4781 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 4782 SDValue CS1 = 4783 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 4784 4785 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 4786 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 4787 } 4788 } 4789 4790 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS, 4791 SDValue RHS, SDValue TVal, 4792 SDValue FVal, const SDLoc &dl, 4793 SelectionDAG &DAG) const { 4794 // Handle f128 first, because it will result in a comparison of some RTLIB 4795 // call result against zero. 4796 if (LHS.getValueType() == MVT::f128) { 4797 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl); 4798 4799 // If softenSetCCOperands returned a scalar, we need to compare the result 4800 // against zero to select between true and false values. 4801 if (!RHS.getNode()) { 4802 RHS = DAG.getConstant(0, dl, LHS.getValueType()); 4803 CC = ISD::SETNE; 4804 } 4805 } 4806 4807 // Also handle f16, for which we need to do a f32 comparison. 4808 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) { 4809 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS); 4810 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS); 4811 } 4812 4813 // Next, handle integers. 4814 if (LHS.getValueType().isInteger()) { 4815 assert((LHS.getValueType() == RHS.getValueType()) && 4816 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64)); 4817 4818 unsigned Opcode = AArch64ISD::CSEL; 4819 4820 // If both the TVal and the FVal are constants, see if we can swap them in 4821 // order to for a CSINV or CSINC out of them. 4822 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal); 4823 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal); 4824 4825 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) { 4826 std::swap(TVal, FVal); 4827 std::swap(CTVal, CFVal); 4828 CC = ISD::getSetCCInverse(CC, true); 4829 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) { 4830 std::swap(TVal, FVal); 4831 std::swap(CTVal, CFVal); 4832 CC = ISD::getSetCCInverse(CC, true); 4833 } else if (TVal.getOpcode() == ISD::XOR) { 4834 // If TVal is a NOT we want to swap TVal and FVal so that we can match 4835 // with a CSINV rather than a CSEL. 4836 if (isAllOnesConstant(TVal.getOperand(1))) { 4837 std::swap(TVal, FVal); 4838 std::swap(CTVal, CFVal); 4839 CC = ISD::getSetCCInverse(CC, true); 4840 } 4841 } else if (TVal.getOpcode() == ISD::SUB) { 4842 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so 4843 // that we can match with a CSNEG rather than a CSEL. 4844 if (isNullConstant(TVal.getOperand(0))) { 4845 std::swap(TVal, FVal); 4846 std::swap(CTVal, CFVal); 4847 CC = ISD::getSetCCInverse(CC, true); 4848 } 4849 } else if (CTVal && CFVal) { 4850 const int64_t TrueVal = CTVal->getSExtValue(); 4851 const int64_t FalseVal = CFVal->getSExtValue(); 4852 bool Swap = false; 4853 4854 // If both TVal and FVal are constants, see if FVal is the 4855 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC 4856 // instead of a CSEL in that case. 4857 if (TrueVal == ~FalseVal) { 4858 Opcode = AArch64ISD::CSINV; 4859 } else if (TrueVal == -FalseVal) { 4860 Opcode = AArch64ISD::CSNEG; 4861 } else if (TVal.getValueType() == MVT::i32) { 4862 // If our operands are only 32-bit wide, make sure we use 32-bit 4863 // arithmetic for the check whether we can use CSINC. This ensures that 4864 // the addition in the check will wrap around properly in case there is 4865 // an overflow (which would not be the case if we do the check with 4866 // 64-bit arithmetic). 4867 const uint32_t TrueVal32 = CTVal->getZExtValue(); 4868 const uint32_t FalseVal32 = CFVal->getZExtValue(); 4869 4870 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) { 4871 Opcode = AArch64ISD::CSINC; 4872 4873 if (TrueVal32 > FalseVal32) { 4874 Swap = true; 4875 } 4876 } 4877 // 64-bit check whether we can use CSINC. 4878 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) { 4879 Opcode = AArch64ISD::CSINC; 4880 4881 if (TrueVal > FalseVal) { 4882 Swap = true; 4883 } 4884 } 4885 4886 // Swap TVal and FVal if necessary. 4887 if (Swap) { 4888 std::swap(TVal, FVal); 4889 std::swap(CTVal, CFVal); 4890 CC = ISD::getSetCCInverse(CC, true); 4891 } 4892 4893 if (Opcode != AArch64ISD::CSEL) { 4894 // Drop FVal since we can get its value by simply inverting/negating 4895 // TVal. 4896 FVal = TVal; 4897 } 4898 } 4899 4900 // Avoid materializing a constant when possible by reusing a known value in 4901 // a register. However, don't perform this optimization if the known value 4902 // is one, zero or negative one in the case of a CSEL. We can always 4903 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the 4904 // FVal, respectively. 4905 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS); 4906 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() && 4907 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) { 4908 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 4909 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to 4910 // "a != C ? x : a" to avoid materializing C. 4911 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ) 4912 TVal = LHS; 4913 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE) 4914 FVal = LHS; 4915 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) { 4916 assert (CTVal && CFVal && "Expected constant operands for CSNEG."); 4917 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to 4918 // avoid materializing C. 4919 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 4920 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) { 4921 Opcode = AArch64ISD::CSINV; 4922 TVal = LHS; 4923 FVal = DAG.getConstant(0, dl, FVal.getValueType()); 4924 } 4925 } 4926 4927 SDValue CCVal; 4928 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl); 4929 EVT VT = TVal.getValueType(); 4930 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp); 4931 } 4932 4933 // Now we know we're dealing with FP values. 4934 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 || 4935 LHS.getValueType() == MVT::f64); 4936 assert(LHS.getValueType() == RHS.getValueType()); 4937 EVT VT = TVal.getValueType(); 4938 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG); 4939 4940 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 4941 // clean. Some of them require two CSELs to implement. 4942 AArch64CC::CondCode CC1, CC2; 4943 changeFPCCToAArch64CC(CC, CC1, CC2); 4944 4945 if (DAG.getTarget().Options.UnsafeFPMath) { 4946 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and 4947 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0. 4948 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS); 4949 if (RHSVal && RHSVal->isZero()) { 4950 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal); 4951 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal); 4952 4953 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) && 4954 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType()) 4955 TVal = LHS; 4956 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) && 4957 CFVal && CFVal->isZero() && 4958 FVal.getValueType() == LHS.getValueType()) 4959 FVal = LHS; 4960 } 4961 } 4962 4963 // Emit first, and possibly only, CSEL. 4964 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32); 4965 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp); 4966 4967 // If we need a second CSEL, emit it, using the output of the first as the 4968 // RHS. We're effectively OR'ing the two CC's together. 4969 if (CC2 != AArch64CC::AL) { 4970 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32); 4971 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp); 4972 } 4973 4974 // Otherwise, return the output of the first CSEL. 4975 return CS1; 4976 } 4977 4978 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op, 4979 SelectionDAG &DAG) const { 4980 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get(); 4981 SDValue LHS = Op.getOperand(0); 4982 SDValue RHS = Op.getOperand(1); 4983 SDValue TVal = Op.getOperand(2); 4984 SDValue FVal = Op.getOperand(3); 4985 SDLoc DL(Op); 4986 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 4987 } 4988 4989 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op, 4990 SelectionDAG &DAG) const { 4991 SDValue CCVal = Op->getOperand(0); 4992 SDValue TVal = Op->getOperand(1); 4993 SDValue FVal = Op->getOperand(2); 4994 SDLoc DL(Op); 4995 4996 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select 4997 // instruction. 4998 if (isOverflowIntrOpRes(CCVal)) { 4999 // Only lower legal XALUO ops. 5000 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0))) 5001 return SDValue(); 5002 5003 AArch64CC::CondCode OFCC; 5004 SDValue Value, Overflow; 5005 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG); 5006 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32); 5007 5008 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, 5009 CCVal, Overflow); 5010 } 5011 5012 // Lower it the same way as we would lower a SELECT_CC node. 5013 ISD::CondCode CC; 5014 SDValue LHS, RHS; 5015 if (CCVal.getOpcode() == ISD::SETCC) { 5016 LHS = CCVal.getOperand(0); 5017 RHS = CCVal.getOperand(1); 5018 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get(); 5019 } else { 5020 LHS = CCVal; 5021 RHS = DAG.getConstant(0, DL, CCVal.getValueType()); 5022 CC = ISD::SETNE; 5023 } 5024 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG); 5025 } 5026 5027 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op, 5028 SelectionDAG &DAG) const { 5029 // Jump table entries as PC relative offsets. No additional tweaking 5030 // is necessary here. Just get the address of the jump table. 5031 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op); 5032 5033 if (getTargetMachine().getCodeModel() == CodeModel::Large && 5034 !Subtarget->isTargetMachO()) { 5035 return getAddrLarge(JT, DAG); 5036 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 5037 return getAddrTiny(JT, DAG); 5038 } 5039 return getAddr(JT, DAG); 5040 } 5041 5042 SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op, 5043 SelectionDAG &DAG) const { 5044 // Jump table entries as PC relative offsets. No additional tweaking 5045 // is necessary here. Just get the address of the jump table. 5046 SDLoc DL(Op); 5047 SDValue JT = Op.getOperand(1); 5048 SDValue Entry = Op.getOperand(2); 5049 int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex(); 5050 5051 SDNode *Dest = 5052 DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT, 5053 Entry, DAG.getTargetJumpTable(JTI, MVT::i32)); 5054 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0), 5055 SDValue(Dest, 0)); 5056 } 5057 5058 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op, 5059 SelectionDAG &DAG) const { 5060 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op); 5061 5062 if (getTargetMachine().getCodeModel() == CodeModel::Large) { 5063 // Use the GOT for the large code model on iOS. 5064 if (Subtarget->isTargetMachO()) { 5065 return getGOT(CP, DAG); 5066 } 5067 return getAddrLarge(CP, DAG); 5068 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 5069 return getAddrTiny(CP, DAG); 5070 } else { 5071 return getAddr(CP, DAG); 5072 } 5073 } 5074 5075 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op, 5076 SelectionDAG &DAG) const { 5077 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op); 5078 if (getTargetMachine().getCodeModel() == CodeModel::Large && 5079 !Subtarget->isTargetMachO()) { 5080 return getAddrLarge(BA, DAG); 5081 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) { 5082 return getAddrTiny(BA, DAG); 5083 } 5084 return getAddr(BA, DAG); 5085 } 5086 5087 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op, 5088 SelectionDAG &DAG) const { 5089 AArch64FunctionInfo *FuncInfo = 5090 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 5091 5092 SDLoc DL(Op); 5093 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), 5094 getPointerTy(DAG.getDataLayout())); 5095 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 5096 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 5097 MachinePointerInfo(SV)); 5098 } 5099 5100 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op, 5101 SelectionDAG &DAG) const { 5102 AArch64FunctionInfo *FuncInfo = 5103 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>(); 5104 5105 SDLoc DL(Op); 5106 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0 5107 ? FuncInfo->getVarArgsGPRIndex() 5108 : FuncInfo->getVarArgsStackIndex(), 5109 getPointerTy(DAG.getDataLayout())); 5110 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 5111 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1), 5112 MachinePointerInfo(SV)); 5113 } 5114 5115 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op, 5116 SelectionDAG &DAG) const { 5117 // The layout of the va_list struct is specified in the AArch64 Procedure Call 5118 // Standard, section B.3. 5119 MachineFunction &MF = DAG.getMachineFunction(); 5120 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>(); 5121 auto PtrVT = getPointerTy(DAG.getDataLayout()); 5122 SDLoc DL(Op); 5123 5124 SDValue Chain = Op.getOperand(0); 5125 SDValue VAList = Op.getOperand(1); 5126 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 5127 SmallVector<SDValue, 4> MemOps; 5128 5129 // void *__stack at offset 0 5130 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT); 5131 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList, 5132 MachinePointerInfo(SV), /* Alignment = */ 8)); 5133 5134 // void *__gr_top at offset 8 5135 int GPRSize = FuncInfo->getVarArgsGPRSize(); 5136 if (GPRSize > 0) { 5137 SDValue GRTop, GRTopAddr; 5138 5139 GRTopAddr = 5140 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT)); 5141 5142 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT); 5143 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop, 5144 DAG.getConstant(GPRSize, DL, PtrVT)); 5145 5146 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr, 5147 MachinePointerInfo(SV, 8), 5148 /* Alignment = */ 8)); 5149 } 5150 5151 // void *__vr_top at offset 16 5152 int FPRSize = FuncInfo->getVarArgsFPRSize(); 5153 if (FPRSize > 0) { 5154 SDValue VRTop, VRTopAddr; 5155 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 5156 DAG.getConstant(16, DL, PtrVT)); 5157 5158 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT); 5159 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop, 5160 DAG.getConstant(FPRSize, DL, PtrVT)); 5161 5162 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr, 5163 MachinePointerInfo(SV, 16), 5164 /* Alignment = */ 8)); 5165 } 5166 5167 // int __gr_offs at offset 24 5168 SDValue GROffsAddr = 5169 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT)); 5170 MemOps.push_back(DAG.getStore( 5171 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr, 5172 MachinePointerInfo(SV, 24), /* Alignment = */ 4)); 5173 5174 // int __vr_offs at offset 28 5175 SDValue VROffsAddr = 5176 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT)); 5177 MemOps.push_back(DAG.getStore( 5178 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr, 5179 MachinePointerInfo(SV, 28), /* Alignment = */ 4)); 5180 5181 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps); 5182 } 5183 5184 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op, 5185 SelectionDAG &DAG) const { 5186 MachineFunction &MF = DAG.getMachineFunction(); 5187 5188 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv())) 5189 return LowerWin64_VASTART(Op, DAG); 5190 else if (Subtarget->isTargetDarwin()) 5191 return LowerDarwin_VASTART(Op, DAG); 5192 else 5193 return LowerAAPCS_VASTART(Op, DAG); 5194 } 5195 5196 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op, 5197 SelectionDAG &DAG) const { 5198 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single 5199 // pointer. 5200 SDLoc DL(Op); 5201 unsigned VaListSize = 5202 Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32; 5203 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue(); 5204 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue(); 5205 5206 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), 5207 Op.getOperand(2), 5208 DAG.getConstant(VaListSize, DL, MVT::i32), 5209 8, false, false, false, MachinePointerInfo(DestSV), 5210 MachinePointerInfo(SrcSV)); 5211 } 5212 5213 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const { 5214 assert(Subtarget->isTargetDarwin() && 5215 "automatic va_arg instruction only works on Darwin"); 5216 5217 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 5218 EVT VT = Op.getValueType(); 5219 SDLoc DL(Op); 5220 SDValue Chain = Op.getOperand(0); 5221 SDValue Addr = Op.getOperand(1); 5222 unsigned Align = Op.getConstantOperandVal(3); 5223 auto PtrVT = getPointerTy(DAG.getDataLayout()); 5224 5225 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V)); 5226 Chain = VAList.getValue(1); 5227 5228 if (Align > 8) { 5229 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2"); 5230 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 5231 DAG.getConstant(Align - 1, DL, PtrVT)); 5232 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList, 5233 DAG.getConstant(-(int64_t)Align, DL, PtrVT)); 5234 } 5235 5236 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext()); 5237 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy); 5238 5239 // Scalar integer and FP values smaller than 64 bits are implicitly extended 5240 // up to 64 bits. At the very least, we have to increase the striding of the 5241 // vaargs list to match this, and for FP values we need to introduce 5242 // FP_ROUND nodes as well. 5243 if (VT.isInteger() && !VT.isVector()) 5244 ArgSize = 8; 5245 bool NeedFPTrunc = false; 5246 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) { 5247 ArgSize = 8; 5248 NeedFPTrunc = true; 5249 } 5250 5251 // Increment the pointer, VAList, to the next vaarg 5252 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList, 5253 DAG.getConstant(ArgSize, DL, PtrVT)); 5254 // Store the incremented VAList to the legalized pointer 5255 SDValue APStore = 5256 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V)); 5257 5258 // Load the actual argument out of the pointer VAList 5259 if (NeedFPTrunc) { 5260 // Load the value as an f64. 5261 SDValue WideFP = 5262 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo()); 5263 // Round the value down to an f32. 5264 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0), 5265 DAG.getIntPtrConstant(1, DL)); 5266 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) }; 5267 // Merge the rounded value with the chain output of the load. 5268 return DAG.getMergeValues(Ops, DL); 5269 } 5270 5271 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo()); 5272 } 5273 5274 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op, 5275 SelectionDAG &DAG) const { 5276 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5277 MFI.setFrameAddressIsTaken(true); 5278 5279 EVT VT = Op.getValueType(); 5280 SDLoc DL(Op); 5281 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5282 SDValue FrameAddr = 5283 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT); 5284 while (Depth--) 5285 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr, 5286 MachinePointerInfo()); 5287 return FrameAddr; 5288 } 5289 5290 SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op, 5291 SelectionDAG &DAG) const { 5292 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo(); 5293 5294 EVT VT = getPointerTy(DAG.getDataLayout()); 5295 SDLoc DL(Op); 5296 int FI = MFI.CreateFixedObject(4, 0, false); 5297 return DAG.getFrameIndex(FI, VT); 5298 } 5299 5300 #define GET_REGISTER_MATCHER 5301 #include "AArch64GenAsmMatcher.inc" 5302 5303 // FIXME? Maybe this could be a TableGen attribute on some registers and 5304 // this table could be generated automatically from RegInfo. 5305 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT, 5306 SelectionDAG &DAG) const { 5307 unsigned Reg = MatchRegisterName(RegName); 5308 if (AArch64::X1 <= Reg && Reg <= AArch64::X28) { 5309 const MCRegisterInfo *MRI = Subtarget->getRegisterInfo(); 5310 unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false); 5311 if (!Subtarget->isXRegisterReserved(DwarfRegNum)) 5312 Reg = 0; 5313 } 5314 if (Reg) 5315 return Reg; 5316 report_fatal_error(Twine("Invalid register name \"" 5317 + StringRef(RegName) + "\".")); 5318 } 5319 5320 SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op, 5321 SelectionDAG &DAG) const { 5322 DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true); 5323 5324 EVT VT = Op.getValueType(); 5325 SDLoc DL(Op); 5326 5327 SDValue FrameAddr = 5328 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT); 5329 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout())); 5330 5331 return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset); 5332 } 5333 5334 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op, 5335 SelectionDAG &DAG) const { 5336 MachineFunction &MF = DAG.getMachineFunction(); 5337 MachineFrameInfo &MFI = MF.getFrameInfo(); 5338 MFI.setReturnAddressIsTaken(true); 5339 5340 EVT VT = Op.getValueType(); 5341 SDLoc DL(Op); 5342 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 5343 if (Depth) { 5344 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG); 5345 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout())); 5346 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 5347 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 5348 MachinePointerInfo()); 5349 } 5350 5351 // Return LR, which contains the return address. Mark it an implicit live-in. 5352 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass); 5353 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT); 5354 } 5355 5356 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two 5357 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 5358 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op, 5359 SelectionDAG &DAG) const { 5360 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5361 EVT VT = Op.getValueType(); 5362 unsigned VTBits = VT.getSizeInBits(); 5363 SDLoc dl(Op); 5364 SDValue ShOpLo = Op.getOperand(0); 5365 SDValue ShOpHi = Op.getOperand(1); 5366 SDValue ShAmt = Op.getOperand(2); 5367 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL; 5368 5369 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS); 5370 5371 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 5372 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 5373 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt); 5374 5375 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which 5376 // is "undef". We wanted 0, so CSEL it directly. 5377 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 5378 ISD::SETEQ, dl, DAG); 5379 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 5380 HiBitsForLo = 5381 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 5382 HiBitsForLo, CCVal, Cmp); 5383 5384 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 5385 DAG.getConstant(VTBits, dl, MVT::i64)); 5386 5387 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt); 5388 SDValue LoForNormalShift = 5389 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo); 5390 5391 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 5392 dl, DAG); 5393 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 5394 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt); 5395 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 5396 LoForNormalShift, CCVal, Cmp); 5397 5398 // AArch64 shifts larger than the register width are wrapped rather than 5399 // clamped, so we can't just emit "hi >> x". 5400 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt); 5401 SDValue HiForBigShift = 5402 Opc == ISD::SRA 5403 ? DAG.getNode(Opc, dl, VT, ShOpHi, 5404 DAG.getConstant(VTBits - 1, dl, MVT::i64)) 5405 : DAG.getConstant(0, dl, VT); 5406 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 5407 HiForNormalShift, CCVal, Cmp); 5408 5409 SDValue Ops[2] = { Lo, Hi }; 5410 return DAG.getMergeValues(Ops, dl); 5411 } 5412 5413 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two 5414 /// i64 values and take a 2 x i64 value to shift plus a shift amount. 5415 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op, 5416 SelectionDAG &DAG) const { 5417 assert(Op.getNumOperands() == 3 && "Not a double-shift!"); 5418 EVT VT = Op.getValueType(); 5419 unsigned VTBits = VT.getSizeInBits(); 5420 SDLoc dl(Op); 5421 SDValue ShOpLo = Op.getOperand(0); 5422 SDValue ShOpHi = Op.getOperand(1); 5423 SDValue ShAmt = Op.getOperand(2); 5424 5425 assert(Op.getOpcode() == ISD::SHL_PARTS); 5426 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, 5427 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt); 5428 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt); 5429 5430 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which 5431 // is "undef". We wanted 0, so CSEL it directly. 5432 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64), 5433 ISD::SETEQ, dl, DAG); 5434 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32); 5435 LoBitsForHi = 5436 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64), 5437 LoBitsForHi, CCVal, Cmp); 5438 5439 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt, 5440 DAG.getConstant(VTBits, dl, MVT::i64)); 5441 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt); 5442 SDValue HiForNormalShift = 5443 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi); 5444 5445 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt); 5446 5447 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE, 5448 dl, DAG); 5449 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32); 5450 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift, 5451 HiForNormalShift, CCVal, Cmp); 5452 5453 // AArch64 shifts of larger than register sizes are wrapped rather than 5454 // clamped, so we can't just emit "lo << a" if a is too big. 5455 SDValue LoForBigShift = DAG.getConstant(0, dl, VT); 5456 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt); 5457 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift, 5458 LoForNormalShift, CCVal, Cmp); 5459 5460 SDValue Ops[2] = { Lo, Hi }; 5461 return DAG.getMergeValues(Ops, dl); 5462 } 5463 5464 bool AArch64TargetLowering::isOffsetFoldingLegal( 5465 const GlobalAddressSDNode *GA) const { 5466 // Offsets are folded in the DAG combine rather than here so that we can 5467 // intelligently choose an offset based on the uses. 5468 return false; 5469 } 5470 5471 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 5472 bool OptForSize) const { 5473 bool IsLegal = false; 5474 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and 5475 // 16-bit case when target has full fp16 support. 5476 // FIXME: We should be able to handle f128 as well with a clever lowering. 5477 const APInt ImmInt = Imm.bitcastToAPInt(); 5478 if (VT == MVT::f64) 5479 IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero(); 5480 else if (VT == MVT::f32) 5481 IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero(); 5482 else if (VT == MVT::f16 && Subtarget->hasFullFP16()) 5483 IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero(); 5484 // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to 5485 // generate that fmov. 5486 5487 // If we can not materialize in immediate field for fmov, check if the 5488 // value can be encoded as the immediate operand of a logical instruction. 5489 // The immediate value will be created with either MOVZ, MOVN, or ORR. 5490 if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) { 5491 // The cost is actually exactly the same for mov+fmov vs. adrp+ldr; 5492 // however the mov+fmov sequence is always better because of the reduced 5493 // cache pressure. The timings are still the same if you consider 5494 // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the 5495 // movw+movk is fused). So we limit up to 2 instrdduction at most. 5496 SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn; 5497 AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(), 5498 Insn); 5499 unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2)); 5500 IsLegal = Insn.size() <= Limit; 5501 } 5502 5503 LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString() 5504 << " imm value: "; Imm.dump();); 5505 return IsLegal; 5506 } 5507 5508 //===----------------------------------------------------------------------===// 5509 // AArch64 Optimization Hooks 5510 //===----------------------------------------------------------------------===// 5511 5512 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode, 5513 SDValue Operand, SelectionDAG &DAG, 5514 int &ExtraSteps) { 5515 EVT VT = Operand.getValueType(); 5516 if (ST->hasNEON() && 5517 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 || 5518 VT == MVT::f32 || VT == MVT::v1f32 || 5519 VT == MVT::v2f32 || VT == MVT::v4f32)) { 5520 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified) 5521 // For the reciprocal estimates, convergence is quadratic, so the number 5522 // of digits is doubled after each iteration. In ARMv8, the accuracy of 5523 // the initial estimate is 2^-8. Thus the number of extra steps to refine 5524 // the result for float (23 mantissa bits) is 2 and for double (52 5525 // mantissa bits) is 3. 5526 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2; 5527 5528 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand); 5529 } 5530 5531 return SDValue(); 5532 } 5533 5534 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand, 5535 SelectionDAG &DAG, int Enabled, 5536 int &ExtraSteps, 5537 bool &UseOneConst, 5538 bool Reciprocal) const { 5539 if (Enabled == ReciprocalEstimate::Enabled || 5540 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt())) 5541 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand, 5542 DAG, ExtraSteps)) { 5543 SDLoc DL(Operand); 5544 EVT VT = Operand.getValueType(); 5545 5546 SDNodeFlags Flags; 5547 Flags.setAllowReassociation(true); 5548 5549 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2) 5550 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N) 5551 for (int i = ExtraSteps; i > 0; --i) { 5552 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate, 5553 Flags); 5554 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags); 5555 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags); 5556 } 5557 if (!Reciprocal) { 5558 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), 5559 VT); 5560 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT); 5561 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ); 5562 5563 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags); 5564 // Correct the result if the operand is 0.0. 5565 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, 5566 VT, Eq, Operand, Estimate); 5567 } 5568 5569 ExtraSteps = 0; 5570 return Estimate; 5571 } 5572 5573 return SDValue(); 5574 } 5575 5576 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand, 5577 SelectionDAG &DAG, int Enabled, 5578 int &ExtraSteps) const { 5579 if (Enabled == ReciprocalEstimate::Enabled) 5580 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand, 5581 DAG, ExtraSteps)) { 5582 SDLoc DL(Operand); 5583 EVT VT = Operand.getValueType(); 5584 5585 SDNodeFlags Flags; 5586 Flags.setAllowReassociation(true); 5587 5588 // Newton reciprocal iteration: E * (2 - X * E) 5589 // AArch64 reciprocal iteration instruction: (2 - M * N) 5590 for (int i = ExtraSteps; i > 0; --i) { 5591 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand, 5592 Estimate, Flags); 5593 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags); 5594 } 5595 5596 ExtraSteps = 0; 5597 return Estimate; 5598 } 5599 5600 return SDValue(); 5601 } 5602 5603 //===----------------------------------------------------------------------===// 5604 // AArch64 Inline Assembly Support 5605 //===----------------------------------------------------------------------===// 5606 5607 // Table of Constraints 5608 // TODO: This is the current set of constraints supported by ARM for the 5609 // compiler, not all of them may make sense. 5610 // 5611 // r - A general register 5612 // w - An FP/SIMD register of some size in the range v0-v31 5613 // x - An FP/SIMD register of some size in the range v0-v15 5614 // I - Constant that can be used with an ADD instruction 5615 // J - Constant that can be used with a SUB instruction 5616 // K - Constant that can be used with a 32-bit logical instruction 5617 // L - Constant that can be used with a 64-bit logical instruction 5618 // M - Constant that can be used as a 32-bit MOV immediate 5619 // N - Constant that can be used as a 64-bit MOV immediate 5620 // Q - A memory reference with base register and no offset 5621 // S - A symbolic address 5622 // Y - Floating point constant zero 5623 // Z - Integer constant zero 5624 // 5625 // Note that general register operands will be output using their 64-bit x 5626 // register name, whatever the size of the variable, unless the asm operand 5627 // is prefixed by the %w modifier. Floating-point and SIMD register operands 5628 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or 5629 // %q modifier. 5630 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const { 5631 // At this point, we have to lower this constraint to something else, so we 5632 // lower it to an "r" or "w". However, by doing this we will force the result 5633 // to be in register, while the X constraint is much more permissive. 5634 // 5635 // Although we are correct (we are free to emit anything, without 5636 // constraints), we might break use cases that would expect us to be more 5637 // efficient and emit something else. 5638 if (!Subtarget->hasFPARMv8()) 5639 return "r"; 5640 5641 if (ConstraintVT.isFloatingPoint()) 5642 return "w"; 5643 5644 if (ConstraintVT.isVector() && 5645 (ConstraintVT.getSizeInBits() == 64 || 5646 ConstraintVT.getSizeInBits() == 128)) 5647 return "w"; 5648 5649 return "r"; 5650 } 5651 5652 /// getConstraintType - Given a constraint letter, return the type of 5653 /// constraint it is for this target. 5654 AArch64TargetLowering::ConstraintType 5655 AArch64TargetLowering::getConstraintType(StringRef Constraint) const { 5656 if (Constraint.size() == 1) { 5657 switch (Constraint[0]) { 5658 default: 5659 break; 5660 case 'z': 5661 return C_Other; 5662 case 'x': 5663 case 'w': 5664 return C_RegisterClass; 5665 // An address with a single base register. Due to the way we 5666 // currently handle addresses it is the same as 'r'. 5667 case 'Q': 5668 return C_Memory; 5669 case 'S': // A symbolic address 5670 return C_Other; 5671 } 5672 } 5673 return TargetLowering::getConstraintType(Constraint); 5674 } 5675 5676 /// Examine constraint type and operand type and determine a weight value. 5677 /// This object must already have been set up with the operand type 5678 /// and the current alternative constraint selected. 5679 TargetLowering::ConstraintWeight 5680 AArch64TargetLowering::getSingleConstraintMatchWeight( 5681 AsmOperandInfo &info, const char *constraint) const { 5682 ConstraintWeight weight = CW_Invalid; 5683 Value *CallOperandVal = info.CallOperandVal; 5684 // If we don't have a value, we can't do a match, 5685 // but allow it at the lowest weight. 5686 if (!CallOperandVal) 5687 return CW_Default; 5688 Type *type = CallOperandVal->getType(); 5689 // Look at the constraint type. 5690 switch (*constraint) { 5691 default: 5692 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint); 5693 break; 5694 case 'x': 5695 case 'w': 5696 if (type->isFloatingPointTy() || type->isVectorTy()) 5697 weight = CW_Register; 5698 break; 5699 case 'z': 5700 weight = CW_Constant; 5701 break; 5702 } 5703 return weight; 5704 } 5705 5706 std::pair<unsigned, const TargetRegisterClass *> 5707 AArch64TargetLowering::getRegForInlineAsmConstraint( 5708 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const { 5709 if (Constraint.size() == 1) { 5710 switch (Constraint[0]) { 5711 case 'r': 5712 if (VT.getSizeInBits() == 64) 5713 return std::make_pair(0U, &AArch64::GPR64commonRegClass); 5714 return std::make_pair(0U, &AArch64::GPR32commonRegClass); 5715 case 'w': 5716 if (!Subtarget->hasFPARMv8()) 5717 break; 5718 if (VT.getSizeInBits() == 16) 5719 return std::make_pair(0U, &AArch64::FPR16RegClass); 5720 if (VT.getSizeInBits() == 32) 5721 return std::make_pair(0U, &AArch64::FPR32RegClass); 5722 if (VT.getSizeInBits() == 64) 5723 return std::make_pair(0U, &AArch64::FPR64RegClass); 5724 if (VT.getSizeInBits() == 128) 5725 return std::make_pair(0U, &AArch64::FPR128RegClass); 5726 break; 5727 // The instructions that this constraint is designed for can 5728 // only take 128-bit registers so just use that regclass. 5729 case 'x': 5730 if (!Subtarget->hasFPARMv8()) 5731 break; 5732 if (VT.getSizeInBits() == 128) 5733 return std::make_pair(0U, &AArch64::FPR128_loRegClass); 5734 break; 5735 } 5736 } 5737 if (StringRef("{cc}").equals_lower(Constraint)) 5738 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass); 5739 5740 // Use the default implementation in TargetLowering to convert the register 5741 // constraint into a member of a register class. 5742 std::pair<unsigned, const TargetRegisterClass *> Res; 5743 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 5744 5745 // Not found as a standard register? 5746 if (!Res.second) { 5747 unsigned Size = Constraint.size(); 5748 if ((Size == 4 || Size == 5) && Constraint[0] == '{' && 5749 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') { 5750 int RegNo; 5751 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo); 5752 if (!Failed && RegNo >= 0 && RegNo <= 31) { 5753 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size. 5754 // By default we'll emit v0-v31 for this unless there's a modifier where 5755 // we'll emit the correct register as well. 5756 if (VT != MVT::Other && VT.getSizeInBits() == 64) { 5757 Res.first = AArch64::FPR64RegClass.getRegister(RegNo); 5758 Res.second = &AArch64::FPR64RegClass; 5759 } else { 5760 Res.first = AArch64::FPR128RegClass.getRegister(RegNo); 5761 Res.second = &AArch64::FPR128RegClass; 5762 } 5763 } 5764 } 5765 } 5766 5767 if (Res.second && !Subtarget->hasFPARMv8() && 5768 !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) && 5769 !AArch64::GPR64allRegClass.hasSubClassEq(Res.second)) 5770 return std::make_pair(0U, nullptr); 5771 5772 return Res; 5773 } 5774 5775 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops 5776 /// vector. If it is invalid, don't add anything to Ops. 5777 void AArch64TargetLowering::LowerAsmOperandForConstraint( 5778 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 5779 SelectionDAG &DAG) const { 5780 SDValue Result; 5781 5782 // Currently only support length 1 constraints. 5783 if (Constraint.length() != 1) 5784 return; 5785 5786 char ConstraintLetter = Constraint[0]; 5787 switch (ConstraintLetter) { 5788 default: 5789 break; 5790 5791 // This set of constraints deal with valid constants for various instructions. 5792 // Validate and return a target constant for them if we can. 5793 case 'z': { 5794 // 'z' maps to xzr or wzr so it needs an input of 0. 5795 if (!isNullConstant(Op)) 5796 return; 5797 5798 if (Op.getValueType() == MVT::i64) 5799 Result = DAG.getRegister(AArch64::XZR, MVT::i64); 5800 else 5801 Result = DAG.getRegister(AArch64::WZR, MVT::i32); 5802 break; 5803 } 5804 case 'S': { 5805 // An absolute symbolic address or label reference. 5806 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 5807 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 5808 GA->getValueType(0)); 5809 } else if (const BlockAddressSDNode *BA = 5810 dyn_cast<BlockAddressSDNode>(Op)) { 5811 Result = 5812 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0)); 5813 } else if (const ExternalSymbolSDNode *ES = 5814 dyn_cast<ExternalSymbolSDNode>(Op)) { 5815 Result = 5816 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0)); 5817 } else 5818 return; 5819 break; 5820 } 5821 5822 case 'I': 5823 case 'J': 5824 case 'K': 5825 case 'L': 5826 case 'M': 5827 case 'N': 5828 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op); 5829 if (!C) 5830 return; 5831 5832 // Grab the value and do some validation. 5833 uint64_t CVal = C->getZExtValue(); 5834 switch (ConstraintLetter) { 5835 // The I constraint applies only to simple ADD or SUB immediate operands: 5836 // i.e. 0 to 4095 with optional shift by 12 5837 // The J constraint applies only to ADD or SUB immediates that would be 5838 // valid when negated, i.e. if [an add pattern] were to be output as a SUB 5839 // instruction [or vice versa], in other words -1 to -4095 with optional 5840 // left shift by 12. 5841 case 'I': 5842 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal)) 5843 break; 5844 return; 5845 case 'J': { 5846 uint64_t NVal = -C->getSExtValue(); 5847 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) { 5848 CVal = C->getSExtValue(); 5849 break; 5850 } 5851 return; 5852 } 5853 // The K and L constraints apply *only* to logical immediates, including 5854 // what used to be the MOVI alias for ORR (though the MOVI alias has now 5855 // been removed and MOV should be used). So these constraints have to 5856 // distinguish between bit patterns that are valid 32-bit or 64-bit 5857 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but 5858 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice 5859 // versa. 5860 case 'K': 5861 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 5862 break; 5863 return; 5864 case 'L': 5865 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 5866 break; 5867 return; 5868 // The M and N constraints are a superset of K and L respectively, for use 5869 // with the MOV (immediate) alias. As well as the logical immediates they 5870 // also match 32 or 64-bit immediates that can be loaded either using a 5871 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca 5872 // (M) or 64-bit 0x1234000000000000 (N) etc. 5873 // As a note some of this code is liberally stolen from the asm parser. 5874 case 'M': { 5875 if (!isUInt<32>(CVal)) 5876 return; 5877 if (AArch64_AM::isLogicalImmediate(CVal, 32)) 5878 break; 5879 if ((CVal & 0xFFFF) == CVal) 5880 break; 5881 if ((CVal & 0xFFFF0000ULL) == CVal) 5882 break; 5883 uint64_t NCVal = ~(uint32_t)CVal; 5884 if ((NCVal & 0xFFFFULL) == NCVal) 5885 break; 5886 if ((NCVal & 0xFFFF0000ULL) == NCVal) 5887 break; 5888 return; 5889 } 5890 case 'N': { 5891 if (AArch64_AM::isLogicalImmediate(CVal, 64)) 5892 break; 5893 if ((CVal & 0xFFFFULL) == CVal) 5894 break; 5895 if ((CVal & 0xFFFF0000ULL) == CVal) 5896 break; 5897 if ((CVal & 0xFFFF00000000ULL) == CVal) 5898 break; 5899 if ((CVal & 0xFFFF000000000000ULL) == CVal) 5900 break; 5901 uint64_t NCVal = ~CVal; 5902 if ((NCVal & 0xFFFFULL) == NCVal) 5903 break; 5904 if ((NCVal & 0xFFFF0000ULL) == NCVal) 5905 break; 5906 if ((NCVal & 0xFFFF00000000ULL) == NCVal) 5907 break; 5908 if ((NCVal & 0xFFFF000000000000ULL) == NCVal) 5909 break; 5910 return; 5911 } 5912 default: 5913 return; 5914 } 5915 5916 // All assembler immediates are 64-bit integers. 5917 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64); 5918 break; 5919 } 5920 5921 if (Result.getNode()) { 5922 Ops.push_back(Result); 5923 return; 5924 } 5925 5926 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 5927 } 5928 5929 //===----------------------------------------------------------------------===// 5930 // AArch64 Advanced SIMD Support 5931 //===----------------------------------------------------------------------===// 5932 5933 /// WidenVector - Given a value in the V64 register class, produce the 5934 /// equivalent value in the V128 register class. 5935 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) { 5936 EVT VT = V64Reg.getValueType(); 5937 unsigned NarrowSize = VT.getVectorNumElements(); 5938 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 5939 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize); 5940 SDLoc DL(V64Reg); 5941 5942 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy), 5943 V64Reg, DAG.getConstant(0, DL, MVT::i32)); 5944 } 5945 5946 /// getExtFactor - Determine the adjustment factor for the position when 5947 /// generating an "extract from vector registers" instruction. 5948 static unsigned getExtFactor(SDValue &V) { 5949 EVT EltType = V.getValueType().getVectorElementType(); 5950 return EltType.getSizeInBits() / 8; 5951 } 5952 5953 /// NarrowVector - Given a value in the V128 register class, produce the 5954 /// equivalent value in the V64 register class. 5955 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) { 5956 EVT VT = V128Reg.getValueType(); 5957 unsigned WideSize = VT.getVectorNumElements(); 5958 MVT EltTy = VT.getVectorElementType().getSimpleVT(); 5959 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2); 5960 SDLoc DL(V128Reg); 5961 5962 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg); 5963 } 5964 5965 // Gather data to see if the operation can be modelled as a 5966 // shuffle in combination with VEXTs. 5967 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op, 5968 SelectionDAG &DAG) const { 5969 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 5970 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n"); 5971 SDLoc dl(Op); 5972 EVT VT = Op.getValueType(); 5973 unsigned NumElts = VT.getVectorNumElements(); 5974 5975 struct ShuffleSourceInfo { 5976 SDValue Vec; 5977 unsigned MinElt; 5978 unsigned MaxElt; 5979 5980 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to 5981 // be compatible with the shuffle we intend to construct. As a result 5982 // ShuffleVec will be some sliding window into the original Vec. 5983 SDValue ShuffleVec; 5984 5985 // Code should guarantee that element i in Vec starts at element "WindowBase 5986 // + i * WindowScale in ShuffleVec". 5987 int WindowBase; 5988 int WindowScale; 5989 5990 ShuffleSourceInfo(SDValue Vec) 5991 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0), 5992 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {} 5993 5994 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; } 5995 }; 5996 5997 // First gather all vectors used as an immediate source for this BUILD_VECTOR 5998 // node. 5999 SmallVector<ShuffleSourceInfo, 2> Sources; 6000 for (unsigned i = 0; i < NumElts; ++i) { 6001 SDValue V = Op.getOperand(i); 6002 if (V.isUndef()) 6003 continue; 6004 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 6005 !isa<ConstantSDNode>(V.getOperand(1))) { 6006 LLVM_DEBUG( 6007 dbgs() << "Reshuffle failed: " 6008 "a shuffle can only come from building a vector from " 6009 "various elements of other vectors, provided their " 6010 "indices are constant\n"); 6011 return SDValue(); 6012 } 6013 6014 // Add this element source to the list if it's not already there. 6015 SDValue SourceVec = V.getOperand(0); 6016 auto Source = find(Sources, SourceVec); 6017 if (Source == Sources.end()) 6018 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec)); 6019 6020 // Update the minimum and maximum lane number seen. 6021 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue(); 6022 Source->MinElt = std::min(Source->MinElt, EltNo); 6023 Source->MaxElt = std::max(Source->MaxElt, EltNo); 6024 } 6025 6026 if (Sources.size() > 2) { 6027 LLVM_DEBUG( 6028 dbgs() << "Reshuffle failed: currently only do something sane when at " 6029 "most two source vectors are involved\n"); 6030 return SDValue(); 6031 } 6032 6033 // Find out the smallest element size among result and two sources, and use 6034 // it as element size to build the shuffle_vector. 6035 EVT SmallestEltTy = VT.getVectorElementType(); 6036 for (auto &Source : Sources) { 6037 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType(); 6038 if (SrcEltTy.bitsLT(SmallestEltTy)) { 6039 SmallestEltTy = SrcEltTy; 6040 } 6041 } 6042 unsigned ResMultiplier = 6043 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits(); 6044 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6045 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts); 6046 6047 // If the source vector is too wide or too narrow, we may nevertheless be able 6048 // to construct a compatible shuffle either by concatenating it with UNDEF or 6049 // extracting a suitable range of elements. 6050 for (auto &Src : Sources) { 6051 EVT SrcVT = Src.ShuffleVec.getValueType(); 6052 6053 if (SrcVT.getSizeInBits() == VT.getSizeInBits()) 6054 continue; 6055 6056 // This stage of the search produces a source with the same element type as 6057 // the original, but with a total width matching the BUILD_VECTOR output. 6058 EVT EltVT = SrcVT.getVectorElementType(); 6059 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits(); 6060 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts); 6061 6062 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) { 6063 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits()); 6064 // We can pad out the smaller vector for free, so if it's part of a 6065 // shuffle... 6066 Src.ShuffleVec = 6067 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec, 6068 DAG.getUNDEF(Src.ShuffleVec.getValueType())); 6069 continue; 6070 } 6071 6072 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits()); 6073 6074 if (Src.MaxElt - Src.MinElt >= NumSrcElts) { 6075 LLVM_DEBUG( 6076 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n"); 6077 return SDValue(); 6078 } 6079 6080 if (Src.MinElt >= NumSrcElts) { 6081 // The extraction can just take the second half 6082 Src.ShuffleVec = 6083 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6084 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 6085 Src.WindowBase = -NumSrcElts; 6086 } else if (Src.MaxElt < NumSrcElts) { 6087 // The extraction can just take the first half 6088 Src.ShuffleVec = 6089 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6090 DAG.getConstant(0, dl, MVT::i64)); 6091 } else { 6092 // An actual VEXT is needed 6093 SDValue VEXTSrc1 = 6094 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6095 DAG.getConstant(0, dl, MVT::i64)); 6096 SDValue VEXTSrc2 = 6097 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec, 6098 DAG.getConstant(NumSrcElts, dl, MVT::i64)); 6099 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1); 6100 6101 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1, 6102 VEXTSrc2, 6103 DAG.getConstant(Imm, dl, MVT::i32)); 6104 Src.WindowBase = -Src.MinElt; 6105 } 6106 } 6107 6108 // Another possible incompatibility occurs from the vector element types. We 6109 // can fix this by bitcasting the source vectors to the same type we intend 6110 // for the shuffle. 6111 for (auto &Src : Sources) { 6112 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType(); 6113 if (SrcEltTy == SmallestEltTy) 6114 continue; 6115 assert(ShuffleVT.getVectorElementType() == SmallestEltTy); 6116 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec); 6117 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits(); 6118 Src.WindowBase *= Src.WindowScale; 6119 } 6120 6121 // Final sanity check before we try to actually produce a shuffle. 6122 LLVM_DEBUG(for (auto Src 6123 : Sources) 6124 assert(Src.ShuffleVec.getValueType() == ShuffleVT);); 6125 6126 // The stars all align, our next step is to produce the mask for the shuffle. 6127 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1); 6128 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits(); 6129 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) { 6130 SDValue Entry = Op.getOperand(i); 6131 if (Entry.isUndef()) 6132 continue; 6133 6134 auto Src = find(Sources, Entry.getOperand(0)); 6135 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue(); 6136 6137 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit 6138 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this 6139 // segment. 6140 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType(); 6141 int BitsDefined = 6142 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits()); 6143 int LanesDefined = BitsDefined / BitsPerShuffleLane; 6144 6145 // This source is expected to fill ResMultiplier lanes of the final shuffle, 6146 // starting at the appropriate offset. 6147 int *LaneMask = &Mask[i * ResMultiplier]; 6148 6149 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase; 6150 ExtractBase += NumElts * (Src - Sources.begin()); 6151 for (int j = 0; j < LanesDefined; ++j) 6152 LaneMask[j] = ExtractBase + j; 6153 } 6154 6155 // Final check before we try to produce nonsense... 6156 if (!isShuffleMaskLegal(Mask, ShuffleVT)) { 6157 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n"); 6158 return SDValue(); 6159 } 6160 6161 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) }; 6162 for (unsigned i = 0; i < Sources.size(); ++i) 6163 ShuffleOps[i] = Sources[i].ShuffleVec; 6164 6165 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0], 6166 ShuffleOps[1], Mask); 6167 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle); 6168 6169 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump(); 6170 dbgs() << "Reshuffle, creating node: "; V.dump();); 6171 6172 return V; 6173 } 6174 6175 // check if an EXT instruction can handle the shuffle mask when the 6176 // vector sources of the shuffle are the same. 6177 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) { 6178 unsigned NumElts = VT.getVectorNumElements(); 6179 6180 // Assume that the first shuffle index is not UNDEF. Fail if it is. 6181 if (M[0] < 0) 6182 return false; 6183 6184 Imm = M[0]; 6185 6186 // If this is a VEXT shuffle, the immediate value is the index of the first 6187 // element. The other shuffle indices must be the successive elements after 6188 // the first one. 6189 unsigned ExpectedElt = Imm; 6190 for (unsigned i = 1; i < NumElts; ++i) { 6191 // Increment the expected index. If it wraps around, just follow it 6192 // back to index zero and keep going. 6193 ++ExpectedElt; 6194 if (ExpectedElt == NumElts) 6195 ExpectedElt = 0; 6196 6197 if (M[i] < 0) 6198 continue; // ignore UNDEF indices 6199 if (ExpectedElt != static_cast<unsigned>(M[i])) 6200 return false; 6201 } 6202 6203 return true; 6204 } 6205 6206 // check if an EXT instruction can handle the shuffle mask when the 6207 // vector sources of the shuffle are different. 6208 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT, 6209 unsigned &Imm) { 6210 // Look for the first non-undef element. 6211 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; }); 6212 6213 // Benefit form APInt to handle overflow when calculating expected element. 6214 unsigned NumElts = VT.getVectorNumElements(); 6215 unsigned MaskBits = APInt(32, NumElts * 2).logBase2(); 6216 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1); 6217 // The following shuffle indices must be the successive elements after the 6218 // first real element. 6219 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(), 6220 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;}); 6221 if (FirstWrongElt != M.end()) 6222 return false; 6223 6224 // The index of an EXT is the first element if it is not UNDEF. 6225 // Watch out for the beginning UNDEFs. The EXT index should be the expected 6226 // value of the first element. E.g. 6227 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>. 6228 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>. 6229 // ExpectedElt is the last mask index plus 1. 6230 Imm = ExpectedElt.getZExtValue(); 6231 6232 // There are two difference cases requiring to reverse input vectors. 6233 // For example, for vector <4 x i32> we have the following cases, 6234 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>) 6235 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>) 6236 // For both cases, we finally use mask <5, 6, 7, 0>, which requires 6237 // to reverse two input vectors. 6238 if (Imm < NumElts) 6239 ReverseEXT = true; 6240 else 6241 Imm -= NumElts; 6242 6243 return true; 6244 } 6245 6246 /// isREVMask - Check if a vector shuffle corresponds to a REV 6247 /// instruction with the specified blocksize. (The order of the elements 6248 /// within each block of the vector is reversed.) 6249 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) { 6250 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) && 6251 "Only possible block sizes for REV are: 16, 32, 64"); 6252 6253 unsigned EltSz = VT.getScalarSizeInBits(); 6254 if (EltSz == 64) 6255 return false; 6256 6257 unsigned NumElts = VT.getVectorNumElements(); 6258 unsigned BlockElts = M[0] + 1; 6259 // If the first shuffle index is UNDEF, be optimistic. 6260 if (M[0] < 0) 6261 BlockElts = BlockSize / EltSz; 6262 6263 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz) 6264 return false; 6265 6266 for (unsigned i = 0; i < NumElts; ++i) { 6267 if (M[i] < 0) 6268 continue; // ignore UNDEF indices 6269 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts)) 6270 return false; 6271 } 6272 6273 return true; 6274 } 6275 6276 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6277 unsigned NumElts = VT.getVectorNumElements(); 6278 WhichResult = (M[0] == 0 ? 0 : 1); 6279 unsigned Idx = WhichResult * NumElts / 2; 6280 for (unsigned i = 0; i != NumElts; i += 2) { 6281 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 6282 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts)) 6283 return false; 6284 Idx += 1; 6285 } 6286 6287 return true; 6288 } 6289 6290 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6291 unsigned NumElts = VT.getVectorNumElements(); 6292 WhichResult = (M[0] == 0 ? 0 : 1); 6293 for (unsigned i = 0; i != NumElts; ++i) { 6294 if (M[i] < 0) 6295 continue; // ignore UNDEF indices 6296 if ((unsigned)M[i] != 2 * i + WhichResult) 6297 return false; 6298 } 6299 6300 return true; 6301 } 6302 6303 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6304 unsigned NumElts = VT.getVectorNumElements(); 6305 if (NumElts % 2 != 0) 6306 return false; 6307 WhichResult = (M[0] == 0 ? 0 : 1); 6308 for (unsigned i = 0; i < NumElts; i += 2) { 6309 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 6310 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult)) 6311 return false; 6312 } 6313 return true; 6314 } 6315 6316 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of 6317 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6318 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>. 6319 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6320 unsigned NumElts = VT.getVectorNumElements(); 6321 if (NumElts % 2 != 0) 6322 return false; 6323 WhichResult = (M[0] == 0 ? 0 : 1); 6324 unsigned Idx = WhichResult * NumElts / 2; 6325 for (unsigned i = 0; i != NumElts; i += 2) { 6326 if ((M[i] >= 0 && (unsigned)M[i] != Idx) || 6327 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx)) 6328 return false; 6329 Idx += 1; 6330 } 6331 6332 return true; 6333 } 6334 6335 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of 6336 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6337 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>, 6338 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6339 unsigned Half = VT.getVectorNumElements() / 2; 6340 WhichResult = (M[0] == 0 ? 0 : 1); 6341 for (unsigned j = 0; j != 2; ++j) { 6342 unsigned Idx = WhichResult; 6343 for (unsigned i = 0; i != Half; ++i) { 6344 int MIdx = M[i + j * Half]; 6345 if (MIdx >= 0 && (unsigned)MIdx != Idx) 6346 return false; 6347 Idx += 2; 6348 } 6349 } 6350 6351 return true; 6352 } 6353 6354 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of 6355 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef". 6356 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>. 6357 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) { 6358 unsigned NumElts = VT.getVectorNumElements(); 6359 if (NumElts % 2 != 0) 6360 return false; 6361 WhichResult = (M[0] == 0 ? 0 : 1); 6362 for (unsigned i = 0; i < NumElts; i += 2) { 6363 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) || 6364 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult)) 6365 return false; 6366 } 6367 return true; 6368 } 6369 6370 static bool isINSMask(ArrayRef<int> M, int NumInputElements, 6371 bool &DstIsLeft, int &Anomaly) { 6372 if (M.size() != static_cast<size_t>(NumInputElements)) 6373 return false; 6374 6375 int NumLHSMatch = 0, NumRHSMatch = 0; 6376 int LastLHSMismatch = -1, LastRHSMismatch = -1; 6377 6378 for (int i = 0; i < NumInputElements; ++i) { 6379 if (M[i] == -1) { 6380 ++NumLHSMatch; 6381 ++NumRHSMatch; 6382 continue; 6383 } 6384 6385 if (M[i] == i) 6386 ++NumLHSMatch; 6387 else 6388 LastLHSMismatch = i; 6389 6390 if (M[i] == i + NumInputElements) 6391 ++NumRHSMatch; 6392 else 6393 LastRHSMismatch = i; 6394 } 6395 6396 if (NumLHSMatch == NumInputElements - 1) { 6397 DstIsLeft = true; 6398 Anomaly = LastLHSMismatch; 6399 return true; 6400 } else if (NumRHSMatch == NumInputElements - 1) { 6401 DstIsLeft = false; 6402 Anomaly = LastRHSMismatch; 6403 return true; 6404 } 6405 6406 return false; 6407 } 6408 6409 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) { 6410 if (VT.getSizeInBits() != 128) 6411 return false; 6412 6413 unsigned NumElts = VT.getVectorNumElements(); 6414 6415 for (int I = 0, E = NumElts / 2; I != E; I++) { 6416 if (Mask[I] != I) 6417 return false; 6418 } 6419 6420 int Offset = NumElts / 2; 6421 for (int I = NumElts / 2, E = NumElts; I != E; I++) { 6422 if (Mask[I] != I + SplitLHS * Offset) 6423 return false; 6424 } 6425 6426 return true; 6427 } 6428 6429 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) { 6430 SDLoc DL(Op); 6431 EVT VT = Op.getValueType(); 6432 SDValue V0 = Op.getOperand(0); 6433 SDValue V1 = Op.getOperand(1); 6434 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask(); 6435 6436 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() || 6437 VT.getVectorElementType() != V1.getValueType().getVectorElementType()) 6438 return SDValue(); 6439 6440 bool SplitV0 = V0.getValueSizeInBits() == 128; 6441 6442 if (!isConcatMask(Mask, VT, SplitV0)) 6443 return SDValue(); 6444 6445 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 6446 VT.getVectorNumElements() / 2); 6447 if (SplitV0) { 6448 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0, 6449 DAG.getConstant(0, DL, MVT::i64)); 6450 } 6451 if (V1.getValueSizeInBits() == 128) { 6452 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1, 6453 DAG.getConstant(0, DL, MVT::i64)); 6454 } 6455 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1); 6456 } 6457 6458 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit 6459 /// the specified operations to build the shuffle. 6460 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS, 6461 SDValue RHS, SelectionDAG &DAG, 6462 const SDLoc &dl) { 6463 unsigned OpNum = (PFEntry >> 26) & 0x0F; 6464 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1); 6465 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1); 6466 6467 enum { 6468 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3> 6469 OP_VREV, 6470 OP_VDUP0, 6471 OP_VDUP1, 6472 OP_VDUP2, 6473 OP_VDUP3, 6474 OP_VEXT1, 6475 OP_VEXT2, 6476 OP_VEXT3, 6477 OP_VUZPL, // VUZP, left result 6478 OP_VUZPR, // VUZP, right result 6479 OP_VZIPL, // VZIP, left result 6480 OP_VZIPR, // VZIP, right result 6481 OP_VTRNL, // VTRN, left result 6482 OP_VTRNR // VTRN, right result 6483 }; 6484 6485 if (OpNum == OP_COPY) { 6486 if (LHSID == (1 * 9 + 2) * 9 + 3) 6487 return LHS; 6488 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!"); 6489 return RHS; 6490 } 6491 6492 SDValue OpLHS, OpRHS; 6493 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl); 6494 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl); 6495 EVT VT = OpLHS.getValueType(); 6496 6497 switch (OpNum) { 6498 default: 6499 llvm_unreachable("Unknown shuffle opcode!"); 6500 case OP_VREV: 6501 // VREV divides the vector in half and swaps within the half. 6502 if (VT.getVectorElementType() == MVT::i32 || 6503 VT.getVectorElementType() == MVT::f32) 6504 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS); 6505 // vrev <4 x i16> -> REV32 6506 if (VT.getVectorElementType() == MVT::i16 || 6507 VT.getVectorElementType() == MVT::f16) 6508 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS); 6509 // vrev <4 x i8> -> REV16 6510 assert(VT.getVectorElementType() == MVT::i8); 6511 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS); 6512 case OP_VDUP0: 6513 case OP_VDUP1: 6514 case OP_VDUP2: 6515 case OP_VDUP3: { 6516 EVT EltTy = VT.getVectorElementType(); 6517 unsigned Opcode; 6518 if (EltTy == MVT::i8) 6519 Opcode = AArch64ISD::DUPLANE8; 6520 else if (EltTy == MVT::i16 || EltTy == MVT::f16) 6521 Opcode = AArch64ISD::DUPLANE16; 6522 else if (EltTy == MVT::i32 || EltTy == MVT::f32) 6523 Opcode = AArch64ISD::DUPLANE32; 6524 else if (EltTy == MVT::i64 || EltTy == MVT::f64) 6525 Opcode = AArch64ISD::DUPLANE64; 6526 else 6527 llvm_unreachable("Invalid vector element type?"); 6528 6529 if (VT.getSizeInBits() == 64) 6530 OpLHS = WidenVector(OpLHS, DAG); 6531 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64); 6532 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane); 6533 } 6534 case OP_VEXT1: 6535 case OP_VEXT2: 6536 case OP_VEXT3: { 6537 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS); 6538 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS, 6539 DAG.getConstant(Imm, dl, MVT::i32)); 6540 } 6541 case OP_VUZPL: 6542 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, 6543 OpRHS); 6544 case OP_VUZPR: 6545 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, 6546 OpRHS); 6547 case OP_VZIPL: 6548 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, 6549 OpRHS); 6550 case OP_VZIPR: 6551 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, 6552 OpRHS); 6553 case OP_VTRNL: 6554 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, 6555 OpRHS); 6556 case OP_VTRNR: 6557 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, 6558 OpRHS); 6559 } 6560 } 6561 6562 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask, 6563 SelectionDAG &DAG) { 6564 // Check to see if we can use the TBL instruction. 6565 SDValue V1 = Op.getOperand(0); 6566 SDValue V2 = Op.getOperand(1); 6567 SDLoc DL(Op); 6568 6569 EVT EltVT = Op.getValueType().getVectorElementType(); 6570 unsigned BytesPerElt = EltVT.getSizeInBits() / 8; 6571 6572 SmallVector<SDValue, 8> TBLMask; 6573 for (int Val : ShuffleMask) { 6574 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) { 6575 unsigned Offset = Byte + Val * BytesPerElt; 6576 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32)); 6577 } 6578 } 6579 6580 MVT IndexVT = MVT::v8i8; 6581 unsigned IndexLen = 8; 6582 if (Op.getValueSizeInBits() == 128) { 6583 IndexVT = MVT::v16i8; 6584 IndexLen = 16; 6585 } 6586 6587 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1); 6588 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2); 6589 6590 SDValue Shuffle; 6591 if (V2.getNode()->isUndef()) { 6592 if (IndexLen == 8) 6593 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst); 6594 Shuffle = DAG.getNode( 6595 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 6596 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 6597 DAG.getBuildVector(IndexVT, DL, 6598 makeArrayRef(TBLMask.data(), IndexLen))); 6599 } else { 6600 if (IndexLen == 8) { 6601 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst); 6602 Shuffle = DAG.getNode( 6603 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 6604 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst, 6605 DAG.getBuildVector(IndexVT, DL, 6606 makeArrayRef(TBLMask.data(), IndexLen))); 6607 } else { 6608 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we 6609 // cannot currently represent the register constraints on the input 6610 // table registers. 6611 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst, 6612 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0], 6613 // IndexLen)); 6614 Shuffle = DAG.getNode( 6615 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT, 6616 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst, 6617 V2Cst, DAG.getBuildVector(IndexVT, DL, 6618 makeArrayRef(TBLMask.data(), IndexLen))); 6619 } 6620 } 6621 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle); 6622 } 6623 6624 static unsigned getDUPLANEOp(EVT EltType) { 6625 if (EltType == MVT::i8) 6626 return AArch64ISD::DUPLANE8; 6627 if (EltType == MVT::i16 || EltType == MVT::f16) 6628 return AArch64ISD::DUPLANE16; 6629 if (EltType == MVT::i32 || EltType == MVT::f32) 6630 return AArch64ISD::DUPLANE32; 6631 if (EltType == MVT::i64 || EltType == MVT::f64) 6632 return AArch64ISD::DUPLANE64; 6633 6634 llvm_unreachable("Invalid vector element type?"); 6635 } 6636 6637 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, 6638 SelectionDAG &DAG) const { 6639 SDLoc dl(Op); 6640 EVT VT = Op.getValueType(); 6641 6642 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 6643 6644 // Convert shuffles that are directly supported on NEON to target-specific 6645 // DAG nodes, instead of keeping them as shuffles and matching them again 6646 // during code selection. This is more efficient and avoids the possibility 6647 // of inconsistencies between legalization and selection. 6648 ArrayRef<int> ShuffleMask = SVN->getMask(); 6649 6650 SDValue V1 = Op.getOperand(0); 6651 SDValue V2 = Op.getOperand(1); 6652 6653 if (SVN->isSplat()) { 6654 int Lane = SVN->getSplatIndex(); 6655 // If this is undef splat, generate it via "just" vdup, if possible. 6656 if (Lane == -1) 6657 Lane = 0; 6658 6659 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) 6660 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(), 6661 V1.getOperand(0)); 6662 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non- 6663 // constant. If so, we can just reference the lane's definition directly. 6664 if (V1.getOpcode() == ISD::BUILD_VECTOR && 6665 !isa<ConstantSDNode>(V1.getOperand(Lane))) 6666 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane)); 6667 6668 // Otherwise, duplicate from the lane of the input vector. 6669 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType()); 6670 6671 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated 6672 // to make a vector of the same size as this SHUFFLE. We can ignore the 6673 // extract entirely, and canonicalise the concat using WidenVector. 6674 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) { 6675 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue(); 6676 V1 = V1.getOperand(0); 6677 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) { 6678 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2; 6679 Lane -= Idx * VT.getVectorNumElements() / 2; 6680 V1 = WidenVector(V1.getOperand(Idx), DAG); 6681 } else if (VT.getSizeInBits() == 64) 6682 V1 = WidenVector(V1, DAG); 6683 6684 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64)); 6685 } 6686 6687 if (isREVMask(ShuffleMask, VT, 64)) 6688 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2); 6689 if (isREVMask(ShuffleMask, VT, 32)) 6690 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2); 6691 if (isREVMask(ShuffleMask, VT, 16)) 6692 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2); 6693 6694 bool ReverseEXT = false; 6695 unsigned Imm; 6696 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) { 6697 if (ReverseEXT) 6698 std::swap(V1, V2); 6699 Imm *= getExtFactor(V1); 6700 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2, 6701 DAG.getConstant(Imm, dl, MVT::i32)); 6702 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) { 6703 Imm *= getExtFactor(V1); 6704 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1, 6705 DAG.getConstant(Imm, dl, MVT::i32)); 6706 } 6707 6708 unsigned WhichResult; 6709 if (isZIPMask(ShuffleMask, VT, WhichResult)) { 6710 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 6711 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 6712 } 6713 if (isUZPMask(ShuffleMask, VT, WhichResult)) { 6714 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 6715 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 6716 } 6717 if (isTRNMask(ShuffleMask, VT, WhichResult)) { 6718 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 6719 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2); 6720 } 6721 6722 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 6723 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2; 6724 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 6725 } 6726 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 6727 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2; 6728 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 6729 } 6730 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) { 6731 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2; 6732 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1); 6733 } 6734 6735 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG)) 6736 return Concat; 6737 6738 bool DstIsLeft; 6739 int Anomaly; 6740 int NumInputElements = V1.getValueType().getVectorNumElements(); 6741 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) { 6742 SDValue DstVec = DstIsLeft ? V1 : V2; 6743 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64); 6744 6745 SDValue SrcVec = V1; 6746 int SrcLane = ShuffleMask[Anomaly]; 6747 if (SrcLane >= NumInputElements) { 6748 SrcVec = V2; 6749 SrcLane -= VT.getVectorNumElements(); 6750 } 6751 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64); 6752 6753 EVT ScalarVT = VT.getVectorElementType(); 6754 6755 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger()) 6756 ScalarVT = MVT::i32; 6757 6758 return DAG.getNode( 6759 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec, 6760 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV), 6761 DstLaneV); 6762 } 6763 6764 // If the shuffle is not directly supported and it has 4 elements, use 6765 // the PerfectShuffle-generated table to synthesize it from other shuffles. 6766 unsigned NumElts = VT.getVectorNumElements(); 6767 if (NumElts == 4) { 6768 unsigned PFIndexes[4]; 6769 for (unsigned i = 0; i != 4; ++i) { 6770 if (ShuffleMask[i] < 0) 6771 PFIndexes[i] = 8; 6772 else 6773 PFIndexes[i] = ShuffleMask[i]; 6774 } 6775 6776 // Compute the index in the perfect shuffle table. 6777 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 6778 PFIndexes[2] * 9 + PFIndexes[3]; 6779 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 6780 unsigned Cost = (PFEntry >> 30); 6781 6782 if (Cost <= 4) 6783 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl); 6784 } 6785 6786 return GenerateTBL(Op, ShuffleMask, DAG); 6787 } 6788 6789 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits, 6790 APInt &UndefBits) { 6791 EVT VT = BVN->getValueType(0); 6792 APInt SplatBits, SplatUndef; 6793 unsigned SplatBitSize; 6794 bool HasAnyUndefs; 6795 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) { 6796 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize; 6797 6798 for (unsigned i = 0; i < NumSplats; ++i) { 6799 CnstBits <<= SplatBitSize; 6800 UndefBits <<= SplatBitSize; 6801 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits()); 6802 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits()); 6803 } 6804 6805 return true; 6806 } 6807 6808 return false; 6809 } 6810 6811 // Try 64-bit splatted SIMD immediate. 6812 static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 6813 const APInt &Bits) { 6814 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 6815 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 6816 EVT VT = Op.getValueType(); 6817 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64; 6818 6819 if (AArch64_AM::isAdvSIMDModImmType10(Value)) { 6820 Value = AArch64_AM::encodeAdvSIMDModImmType10(Value); 6821 6822 SDLoc dl(Op); 6823 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 6824 DAG.getConstant(Value, dl, MVT::i32)); 6825 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6826 } 6827 } 6828 6829 return SDValue(); 6830 } 6831 6832 // Try 32-bit splatted SIMD immediate. 6833 static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 6834 const APInt &Bits, 6835 const SDValue *LHS = nullptr) { 6836 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 6837 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 6838 EVT VT = Op.getValueType(); 6839 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6840 bool isAdvSIMDModImm = false; 6841 uint64_t Shift; 6842 6843 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) { 6844 Value = AArch64_AM::encodeAdvSIMDModImmType1(Value); 6845 Shift = 0; 6846 } 6847 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) { 6848 Value = AArch64_AM::encodeAdvSIMDModImmType2(Value); 6849 Shift = 8; 6850 } 6851 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) { 6852 Value = AArch64_AM::encodeAdvSIMDModImmType3(Value); 6853 Shift = 16; 6854 } 6855 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) { 6856 Value = AArch64_AM::encodeAdvSIMDModImmType4(Value); 6857 Shift = 24; 6858 } 6859 6860 if (isAdvSIMDModImm) { 6861 SDLoc dl(Op); 6862 SDValue Mov; 6863 6864 if (LHS) 6865 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS, 6866 DAG.getConstant(Value, dl, MVT::i32), 6867 DAG.getConstant(Shift, dl, MVT::i32)); 6868 else 6869 Mov = DAG.getNode(NewOp, dl, MovTy, 6870 DAG.getConstant(Value, dl, MVT::i32), 6871 DAG.getConstant(Shift, dl, MVT::i32)); 6872 6873 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6874 } 6875 } 6876 6877 return SDValue(); 6878 } 6879 6880 // Try 16-bit splatted SIMD immediate. 6881 static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 6882 const APInt &Bits, 6883 const SDValue *LHS = nullptr) { 6884 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 6885 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 6886 EVT VT = Op.getValueType(); 6887 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16; 6888 bool isAdvSIMDModImm = false; 6889 uint64_t Shift; 6890 6891 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) { 6892 Value = AArch64_AM::encodeAdvSIMDModImmType5(Value); 6893 Shift = 0; 6894 } 6895 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) { 6896 Value = AArch64_AM::encodeAdvSIMDModImmType6(Value); 6897 Shift = 8; 6898 } 6899 6900 if (isAdvSIMDModImm) { 6901 SDLoc dl(Op); 6902 SDValue Mov; 6903 6904 if (LHS) 6905 Mov = DAG.getNode(NewOp, dl, MovTy, *LHS, 6906 DAG.getConstant(Value, dl, MVT::i32), 6907 DAG.getConstant(Shift, dl, MVT::i32)); 6908 else 6909 Mov = DAG.getNode(NewOp, dl, MovTy, 6910 DAG.getConstant(Value, dl, MVT::i32), 6911 DAG.getConstant(Shift, dl, MVT::i32)); 6912 6913 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6914 } 6915 } 6916 6917 return SDValue(); 6918 } 6919 6920 // Try 32-bit splatted SIMD immediate with shifted ones. 6921 static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op, 6922 SelectionDAG &DAG, const APInt &Bits) { 6923 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 6924 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 6925 EVT VT = Op.getValueType(); 6926 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32; 6927 bool isAdvSIMDModImm = false; 6928 uint64_t Shift; 6929 6930 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) { 6931 Value = AArch64_AM::encodeAdvSIMDModImmType7(Value); 6932 Shift = 264; 6933 } 6934 else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) { 6935 Value = AArch64_AM::encodeAdvSIMDModImmType8(Value); 6936 Shift = 272; 6937 } 6938 6939 if (isAdvSIMDModImm) { 6940 SDLoc dl(Op); 6941 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 6942 DAG.getConstant(Value, dl, MVT::i32), 6943 DAG.getConstant(Shift, dl, MVT::i32)); 6944 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6945 } 6946 } 6947 6948 return SDValue(); 6949 } 6950 6951 // Try 8-bit splatted SIMD immediate. 6952 static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 6953 const APInt &Bits) { 6954 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 6955 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 6956 EVT VT = Op.getValueType(); 6957 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8; 6958 6959 if (AArch64_AM::isAdvSIMDModImmType9(Value)) { 6960 Value = AArch64_AM::encodeAdvSIMDModImmType9(Value); 6961 6962 SDLoc dl(Op); 6963 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 6964 DAG.getConstant(Value, dl, MVT::i32)); 6965 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6966 } 6967 } 6968 6969 return SDValue(); 6970 } 6971 6972 // Try FP splatted SIMD immediate. 6973 static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG, 6974 const APInt &Bits) { 6975 if (Bits.getHiBits(64) == Bits.getLoBits(64)) { 6976 uint64_t Value = Bits.zextOrTrunc(64).getZExtValue(); 6977 EVT VT = Op.getValueType(); 6978 bool isWide = (VT.getSizeInBits() == 128); 6979 MVT MovTy; 6980 bool isAdvSIMDModImm = false; 6981 6982 if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) { 6983 Value = AArch64_AM::encodeAdvSIMDModImmType11(Value); 6984 MovTy = isWide ? MVT::v4f32 : MVT::v2f32; 6985 } 6986 else if (isWide && 6987 (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) { 6988 Value = AArch64_AM::encodeAdvSIMDModImmType12(Value); 6989 MovTy = MVT::v2f64; 6990 } 6991 6992 if (isAdvSIMDModImm) { 6993 SDLoc dl(Op); 6994 SDValue Mov = DAG.getNode(NewOp, dl, MovTy, 6995 DAG.getConstant(Value, dl, MVT::i32)); 6996 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov); 6997 } 6998 } 6999 7000 return SDValue(); 7001 } 7002 7003 // Specialized code to quickly find if PotentialBVec is a BuildVector that 7004 // consists of only the same constant int value, returned in reference arg 7005 // ConstVal 7006 static bool isAllConstantBuildVector(const SDValue &PotentialBVec, 7007 uint64_t &ConstVal) { 7008 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec); 7009 if (!Bvec) 7010 return false; 7011 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0)); 7012 if (!FirstElt) 7013 return false; 7014 EVT VT = Bvec->getValueType(0); 7015 unsigned NumElts = VT.getVectorNumElements(); 7016 for (unsigned i = 1; i < NumElts; ++i) 7017 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt) 7018 return false; 7019 ConstVal = FirstElt->getZExtValue(); 7020 return true; 7021 } 7022 7023 static unsigned getIntrinsicID(const SDNode *N) { 7024 unsigned Opcode = N->getOpcode(); 7025 switch (Opcode) { 7026 default: 7027 return Intrinsic::not_intrinsic; 7028 case ISD::INTRINSIC_WO_CHAIN: { 7029 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7030 if (IID < Intrinsic::num_intrinsics) 7031 return IID; 7032 return Intrinsic::not_intrinsic; 7033 } 7034 } 7035 } 7036 7037 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)), 7038 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a 7039 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2. 7040 // Also, logical shift right -> sri, with the same structure. 7041 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) { 7042 EVT VT = N->getValueType(0); 7043 7044 if (!VT.isVector()) 7045 return SDValue(); 7046 7047 SDLoc DL(N); 7048 7049 // Is the first op an AND? 7050 const SDValue And = N->getOperand(0); 7051 if (And.getOpcode() != ISD::AND) 7052 return SDValue(); 7053 7054 // Is the second op an shl or lshr? 7055 SDValue Shift = N->getOperand(1); 7056 // This will have been turned into: AArch64ISD::VSHL vector, #shift 7057 // or AArch64ISD::VLSHR vector, #shift 7058 unsigned ShiftOpc = Shift.getOpcode(); 7059 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR)) 7060 return SDValue(); 7061 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR; 7062 7063 // Is the shift amount constant? 7064 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 7065 if (!C2node) 7066 return SDValue(); 7067 7068 // Is the and mask vector all constant? 7069 uint64_t C1; 7070 if (!isAllConstantBuildVector(And.getOperand(1), C1)) 7071 return SDValue(); 7072 7073 // Is C1 == ~C2, taking into account how much one can shift elements of a 7074 // particular size? 7075 uint64_t C2 = C2node->getZExtValue(); 7076 unsigned ElemSizeInBits = VT.getScalarSizeInBits(); 7077 if (C2 > ElemSizeInBits) 7078 return SDValue(); 7079 unsigned ElemMask = (1 << ElemSizeInBits) - 1; 7080 if ((C1 & ElemMask) != (~C2 & ElemMask)) 7081 return SDValue(); 7082 7083 SDValue X = And.getOperand(0); 7084 SDValue Y = Shift.getOperand(0); 7085 7086 unsigned Intrin = 7087 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli; 7088 SDValue ResultSLI = 7089 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 7090 DAG.getConstant(Intrin, DL, MVT::i32), X, Y, 7091 Shift.getOperand(1)); 7092 7093 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n"); 7094 LLVM_DEBUG(N->dump(&DAG)); 7095 LLVM_DEBUG(dbgs() << "into: \n"); 7096 LLVM_DEBUG(ResultSLI->dump(&DAG)); 7097 7098 ++NumShiftInserts; 7099 return ResultSLI; 7100 } 7101 7102 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op, 7103 SelectionDAG &DAG) const { 7104 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2)) 7105 if (EnableAArch64SlrGeneration) { 7106 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG)) 7107 return Res; 7108 } 7109 7110 EVT VT = Op.getValueType(); 7111 7112 SDValue LHS = Op.getOperand(0); 7113 BuildVectorSDNode *BVN = 7114 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode()); 7115 if (!BVN) { 7116 // OR commutes, so try swapping the operands. 7117 LHS = Op.getOperand(1); 7118 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode()); 7119 } 7120 if (!BVN) 7121 return Op; 7122 7123 APInt DefBits(VT.getSizeInBits(), 0); 7124 APInt UndefBits(VT.getSizeInBits(), 0); 7125 if (resolveBuildVector(BVN, DefBits, UndefBits)) { 7126 SDValue NewOp; 7127 7128 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG, 7129 DefBits, &LHS)) || 7130 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG, 7131 DefBits, &LHS))) 7132 return NewOp; 7133 7134 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG, 7135 UndefBits, &LHS)) || 7136 (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG, 7137 UndefBits, &LHS))) 7138 return NewOp; 7139 } 7140 7141 // We can always fall back to a non-immediate OR. 7142 return Op; 7143 } 7144 7145 // Normalize the operands of BUILD_VECTOR. The value of constant operands will 7146 // be truncated to fit element width. 7147 static SDValue NormalizeBuildVector(SDValue Op, 7148 SelectionDAG &DAG) { 7149 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!"); 7150 SDLoc dl(Op); 7151 EVT VT = Op.getValueType(); 7152 EVT EltTy= VT.getVectorElementType(); 7153 7154 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16) 7155 return Op; 7156 7157 SmallVector<SDValue, 16> Ops; 7158 for (SDValue Lane : Op->ops()) { 7159 // For integer vectors, type legalization would have promoted the 7160 // operands already. Otherwise, if Op is a floating-point splat 7161 // (with operands cast to integers), then the only possibilities 7162 // are constants and UNDEFs. 7163 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) { 7164 APInt LowBits(EltTy.getSizeInBits(), 7165 CstLane->getZExtValue()); 7166 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32); 7167 } else if (Lane.getNode()->isUndef()) { 7168 Lane = DAG.getUNDEF(MVT::i32); 7169 } else { 7170 assert(Lane.getValueType() == MVT::i32 && 7171 "Unexpected BUILD_VECTOR operand type"); 7172 } 7173 Ops.push_back(Lane); 7174 } 7175 return DAG.getBuildVector(VT, dl, Ops); 7176 } 7177 7178 static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) { 7179 EVT VT = Op.getValueType(); 7180 7181 APInt DefBits(VT.getSizeInBits(), 0); 7182 APInt UndefBits(VT.getSizeInBits(), 0); 7183 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 7184 if (resolveBuildVector(BVN, DefBits, UndefBits)) { 7185 SDValue NewOp; 7186 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) || 7187 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 7188 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) || 7189 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 7190 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) || 7191 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits))) 7192 return NewOp; 7193 7194 DefBits = ~DefBits; 7195 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) || 7196 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) || 7197 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits))) 7198 return NewOp; 7199 7200 DefBits = UndefBits; 7201 if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) || 7202 (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 7203 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) || 7204 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) || 7205 (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) || 7206 (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits))) 7207 return NewOp; 7208 7209 DefBits = ~UndefBits; 7210 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) || 7211 (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) || 7212 (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits))) 7213 return NewOp; 7214 } 7215 7216 return SDValue(); 7217 } 7218 7219 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op, 7220 SelectionDAG &DAG) const { 7221 EVT VT = Op.getValueType(); 7222 7223 // Try to build a simple constant vector. 7224 Op = NormalizeBuildVector(Op, DAG); 7225 if (VT.isInteger()) { 7226 // Certain vector constants, used to express things like logical NOT and 7227 // arithmetic NEG, are passed through unmodified. This allows special 7228 // patterns for these operations to match, which will lower these constants 7229 // to whatever is proven necessary. 7230 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode()); 7231 if (BVN->isConstant()) 7232 if (ConstantSDNode *Const = BVN->getConstantSplatNode()) { 7233 unsigned BitSize = VT.getVectorElementType().getSizeInBits(); 7234 APInt Val(BitSize, 7235 Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue()); 7236 if (Val.isNullValue() || Val.isAllOnesValue()) 7237 return Op; 7238 } 7239 } 7240 7241 if (SDValue V = ConstantBuildVector(Op, DAG)) 7242 return V; 7243 7244 // Scan through the operands to find some interesting properties we can 7245 // exploit: 7246 // 1) If only one value is used, we can use a DUP, or 7247 // 2) if only the low element is not undef, we can just insert that, or 7248 // 3) if only one constant value is used (w/ some non-constant lanes), 7249 // we can splat the constant value into the whole vector then fill 7250 // in the non-constant lanes. 7251 // 4) FIXME: If different constant values are used, but we can intelligently 7252 // select the values we'll be overwriting for the non-constant 7253 // lanes such that we can directly materialize the vector 7254 // some other way (MOVI, e.g.), we can be sneaky. 7255 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP. 7256 SDLoc dl(Op); 7257 unsigned NumElts = VT.getVectorNumElements(); 7258 bool isOnlyLowElement = true; 7259 bool usesOnlyOneValue = true; 7260 bool usesOnlyOneConstantValue = true; 7261 bool isConstant = true; 7262 bool AllLanesExtractElt = true; 7263 unsigned NumConstantLanes = 0; 7264 SDValue Value; 7265 SDValue ConstantValue; 7266 for (unsigned i = 0; i < NumElts; ++i) { 7267 SDValue V = Op.getOperand(i); 7268 if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 7269 AllLanesExtractElt = false; 7270 if (V.isUndef()) 7271 continue; 7272 if (i > 0) 7273 isOnlyLowElement = false; 7274 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V)) 7275 isConstant = false; 7276 7277 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) { 7278 ++NumConstantLanes; 7279 if (!ConstantValue.getNode()) 7280 ConstantValue = V; 7281 else if (ConstantValue != V) 7282 usesOnlyOneConstantValue = false; 7283 } 7284 7285 if (!Value.getNode()) 7286 Value = V; 7287 else if (V != Value) 7288 usesOnlyOneValue = false; 7289 } 7290 7291 if (!Value.getNode()) { 7292 LLVM_DEBUG( 7293 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n"); 7294 return DAG.getUNDEF(VT); 7295 } 7296 7297 // Convert BUILD_VECTOR where all elements but the lowest are undef into 7298 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector 7299 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR. 7300 if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) { 7301 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 " 7302 "SCALAR_TO_VECTOR node\n"); 7303 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value); 7304 } 7305 7306 if (AllLanesExtractElt) { 7307 SDNode *Vector = nullptr; 7308 bool Even = false; 7309 bool Odd = false; 7310 // Check whether the extract elements match the Even pattern <0,2,4,...> or 7311 // the Odd pattern <1,3,5,...>. 7312 for (unsigned i = 0; i < NumElts; ++i) { 7313 SDValue V = Op.getOperand(i); 7314 const SDNode *N = V.getNode(); 7315 if (!isa<ConstantSDNode>(N->getOperand(1))) 7316 break; 7317 SDValue N0 = N->getOperand(0); 7318 7319 // All elements are extracted from the same vector. 7320 if (!Vector) { 7321 Vector = N0.getNode(); 7322 // Check that the type of EXTRACT_VECTOR_ELT matches the type of 7323 // BUILD_VECTOR. 7324 if (VT.getVectorElementType() != 7325 N0.getValueType().getVectorElementType()) 7326 break; 7327 } else if (Vector != N0.getNode()) { 7328 Odd = false; 7329 Even = false; 7330 break; 7331 } 7332 7333 // Extracted values are either at Even indices <0,2,4,...> or at Odd 7334 // indices <1,3,5,...>. 7335 uint64_t Val = N->getConstantOperandVal(1); 7336 if (Val == 2 * i) { 7337 Even = true; 7338 continue; 7339 } 7340 if (Val - 1 == 2 * i) { 7341 Odd = true; 7342 continue; 7343 } 7344 7345 // Something does not match: abort. 7346 Odd = false; 7347 Even = false; 7348 break; 7349 } 7350 if (Even || Odd) { 7351 SDValue LHS = 7352 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0), 7353 DAG.getConstant(0, dl, MVT::i64)); 7354 SDValue RHS = 7355 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0), 7356 DAG.getConstant(NumElts, dl, MVT::i64)); 7357 7358 if (Even && !Odd) 7359 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS, 7360 RHS); 7361 if (Odd && !Even) 7362 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS, 7363 RHS); 7364 } 7365 } 7366 7367 // Use DUP for non-constant splats. For f32 constant splats, reduce to 7368 // i32 and try again. 7369 if (usesOnlyOneValue) { 7370 if (!isConstant) { 7371 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT || 7372 Value.getValueType() != VT) { 7373 LLVM_DEBUG( 7374 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n"); 7375 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value); 7376 } 7377 7378 // This is actually a DUPLANExx operation, which keeps everything vectory. 7379 7380 SDValue Lane = Value.getOperand(1); 7381 Value = Value.getOperand(0); 7382 if (Value.getValueSizeInBits() == 64) { 7383 LLVM_DEBUG( 7384 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, " 7385 "widening it\n"); 7386 Value = WidenVector(Value, DAG); 7387 } 7388 7389 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType()); 7390 return DAG.getNode(Opcode, dl, VT, Value, Lane); 7391 } 7392 7393 if (VT.getVectorElementType().isFloatingPoint()) { 7394 SmallVector<SDValue, 8> Ops; 7395 EVT EltTy = VT.getVectorElementType(); 7396 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) && 7397 "Unsupported floating-point vector type"); 7398 LLVM_DEBUG( 7399 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int " 7400 "BITCASTS, and try again\n"); 7401 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits()); 7402 for (unsigned i = 0; i < NumElts; ++i) 7403 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i))); 7404 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts); 7405 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops); 7406 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: "; 7407 Val.dump();); 7408 Val = LowerBUILD_VECTOR(Val, DAG); 7409 if (Val.getNode()) 7410 return DAG.getNode(ISD::BITCAST, dl, VT, Val); 7411 } 7412 } 7413 7414 // If there was only one constant value used and for more than one lane, 7415 // start by splatting that value, then replace the non-constant lanes. This 7416 // is better than the default, which will perform a separate initialization 7417 // for each lane. 7418 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) { 7419 // Firstly, try to materialize the splat constant. 7420 SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue), 7421 Val = ConstantBuildVector(Vec, DAG); 7422 if (!Val) { 7423 // Otherwise, materialize the constant and splat it. 7424 Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue); 7425 DAG.ReplaceAllUsesWith(Vec.getNode(), &Val); 7426 } 7427 7428 // Now insert the non-constant lanes. 7429 for (unsigned i = 0; i < NumElts; ++i) { 7430 SDValue V = Op.getOperand(i); 7431 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 7432 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) 7433 // Note that type legalization likely mucked about with the VT of the 7434 // source operand, so we may have to convert it here before inserting. 7435 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx); 7436 } 7437 return Val; 7438 } 7439 7440 // This will generate a load from the constant pool. 7441 if (isConstant) { 7442 LLVM_DEBUG( 7443 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default " 7444 "expansion\n"); 7445 return SDValue(); 7446 } 7447 7448 // Empirical tests suggest this is rarely worth it for vectors of length <= 2. 7449 if (NumElts >= 4) { 7450 if (SDValue shuffle = ReconstructShuffle(Op, DAG)) 7451 return shuffle; 7452 } 7453 7454 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we 7455 // know the default expansion would otherwise fall back on something even 7456 // worse. For a vector with one or two non-undef values, that's 7457 // scalar_to_vector for the elements followed by a shuffle (provided the 7458 // shuffle is valid for the target) and materialization element by element 7459 // on the stack followed by a load for everything else. 7460 if (!isConstant && !usesOnlyOneValue) { 7461 LLVM_DEBUG( 7462 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence " 7463 "of INSERT_VECTOR_ELT\n"); 7464 7465 SDValue Vec = DAG.getUNDEF(VT); 7466 SDValue Op0 = Op.getOperand(0); 7467 unsigned i = 0; 7468 7469 // Use SCALAR_TO_VECTOR for lane zero to 7470 // a) Avoid a RMW dependency on the full vector register, and 7471 // b) Allow the register coalescer to fold away the copy if the 7472 // value is already in an S or D register, and we're forced to emit an 7473 // INSERT_SUBREG that we can't fold anywhere. 7474 // 7475 // We also allow types like i8 and i16 which are illegal scalar but legal 7476 // vector element types. After type-legalization the inserted value is 7477 // extended (i32) and it is safe to cast them to the vector type by ignoring 7478 // the upper bits of the lowest lane (e.g. v8i8, v4i16). 7479 if (!Op0.isUndef()) { 7480 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n"); 7481 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0); 7482 ++i; 7483 } 7484 LLVM_DEBUG(if (i < NumElts) dbgs() 7485 << "Creating nodes for the other vector elements:\n";); 7486 for (; i < NumElts; ++i) { 7487 SDValue V = Op.getOperand(i); 7488 if (V.isUndef()) 7489 continue; 7490 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64); 7491 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx); 7492 } 7493 return Vec; 7494 } 7495 7496 LLVM_DEBUG( 7497 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find " 7498 "better alternative\n"); 7499 return SDValue(); 7500 } 7501 7502 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, 7503 SelectionDAG &DAG) const { 7504 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!"); 7505 7506 // Check for non-constant or out of range lane. 7507 EVT VT = Op.getOperand(0).getValueType(); 7508 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2)); 7509 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 7510 return SDValue(); 7511 7512 7513 // Insertion/extraction are legal for V128 types. 7514 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 7515 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 7516 VT == MVT::v8f16) 7517 return Op; 7518 7519 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 7520 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16) 7521 return SDValue(); 7522 7523 // For V64 types, we perform insertion by expanding the value 7524 // to a V128 type and perform the insertion on that. 7525 SDLoc DL(Op); 7526 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 7527 EVT WideTy = WideVec.getValueType(); 7528 7529 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec, 7530 Op.getOperand(1), Op.getOperand(2)); 7531 // Re-narrow the resultant vector. 7532 return NarrowVector(Node, DAG); 7533 } 7534 7535 SDValue 7536 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, 7537 SelectionDAG &DAG) const { 7538 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!"); 7539 7540 // Check for non-constant or out of range lane. 7541 EVT VT = Op.getOperand(0).getValueType(); 7542 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 7543 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements()) 7544 return SDValue(); 7545 7546 7547 // Insertion/extraction are legal for V128 types. 7548 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 || 7549 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 || 7550 VT == MVT::v8f16) 7551 return Op; 7552 7553 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 && 7554 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16) 7555 return SDValue(); 7556 7557 // For V64 types, we perform extraction by expanding the value 7558 // to a V128 type and perform the extraction on that. 7559 SDLoc DL(Op); 7560 SDValue WideVec = WidenVector(Op.getOperand(0), DAG); 7561 EVT WideTy = WideVec.getValueType(); 7562 7563 EVT ExtrTy = WideTy.getVectorElementType(); 7564 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8) 7565 ExtrTy = MVT::i32; 7566 7567 // For extractions, we just return the result directly. 7568 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec, 7569 Op.getOperand(1)); 7570 } 7571 7572 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, 7573 SelectionDAG &DAG) const { 7574 EVT VT = Op.getOperand(0).getValueType(); 7575 SDLoc dl(Op); 7576 // Just in case... 7577 if (!VT.isVector()) 7578 return SDValue(); 7579 7580 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 7581 if (!Cst) 7582 return SDValue(); 7583 unsigned Val = Cst->getZExtValue(); 7584 7585 unsigned Size = Op.getValueSizeInBits(); 7586 7587 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel. 7588 if (Val == 0) 7589 return Op; 7590 7591 // If this is extracting the upper 64-bits of a 128-bit vector, we match 7592 // that directly. 7593 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64) 7594 return Op; 7595 7596 return SDValue(); 7597 } 7598 7599 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 7600 if (VT.getVectorNumElements() == 4 && 7601 (VT.is128BitVector() || VT.is64BitVector())) { 7602 unsigned PFIndexes[4]; 7603 for (unsigned i = 0; i != 4; ++i) { 7604 if (M[i] < 0) 7605 PFIndexes[i] = 8; 7606 else 7607 PFIndexes[i] = M[i]; 7608 } 7609 7610 // Compute the index in the perfect shuffle table. 7611 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 + 7612 PFIndexes[2] * 9 + PFIndexes[3]; 7613 unsigned PFEntry = PerfectShuffleTable[PFTableIndex]; 7614 unsigned Cost = (PFEntry >> 30); 7615 7616 if (Cost <= 4) 7617 return true; 7618 } 7619 7620 bool DummyBool; 7621 int DummyInt; 7622 unsigned DummyUnsigned; 7623 7624 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) || 7625 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) || 7626 isEXTMask(M, VT, DummyBool, DummyUnsigned) || 7627 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM. 7628 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) || 7629 isZIPMask(M, VT, DummyUnsigned) || 7630 isTRN_v_undef_Mask(M, VT, DummyUnsigned) || 7631 isUZP_v_undef_Mask(M, VT, DummyUnsigned) || 7632 isZIP_v_undef_Mask(M, VT, DummyUnsigned) || 7633 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) || 7634 isConcatMask(M, VT, VT.getSizeInBits() == 128)); 7635 } 7636 7637 /// getVShiftImm - Check if this is a valid build_vector for the immediate 7638 /// operand of a vector shift operation, where all the elements of the 7639 /// build_vector must have the same constant integer value. 7640 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) { 7641 // Ignore bit_converts. 7642 while (Op.getOpcode() == ISD::BITCAST) 7643 Op = Op.getOperand(0); 7644 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode()); 7645 APInt SplatBits, SplatUndef; 7646 unsigned SplatBitSize; 7647 bool HasAnyUndefs; 7648 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, 7649 HasAnyUndefs, ElementBits) || 7650 SplatBitSize > ElementBits) 7651 return false; 7652 Cnt = SplatBits.getSExtValue(); 7653 return true; 7654 } 7655 7656 /// isVShiftLImm - Check if this is a valid build_vector for the immediate 7657 /// operand of a vector shift left operation. That value must be in the range: 7658 /// 0 <= Value < ElementBits for a left shift; or 7659 /// 0 <= Value <= ElementBits for a long left shift. 7660 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) { 7661 assert(VT.isVector() && "vector shift count is not a vector type"); 7662 int64_t ElementBits = VT.getScalarSizeInBits(); 7663 if (!getVShiftImm(Op, ElementBits, Cnt)) 7664 return false; 7665 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits); 7666 } 7667 7668 /// isVShiftRImm - Check if this is a valid build_vector for the immediate 7669 /// operand of a vector shift right operation. The value must be in the range: 7670 /// 1 <= Value <= ElementBits for a right shift; or 7671 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) { 7672 assert(VT.isVector() && "vector shift count is not a vector type"); 7673 int64_t ElementBits = VT.getScalarSizeInBits(); 7674 if (!getVShiftImm(Op, ElementBits, Cnt)) 7675 return false; 7676 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits)); 7677 } 7678 7679 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op, 7680 SelectionDAG &DAG) const { 7681 EVT VT = Op.getValueType(); 7682 SDLoc DL(Op); 7683 int64_t Cnt; 7684 7685 if (!Op.getOperand(1).getValueType().isVector()) 7686 return Op; 7687 unsigned EltSize = VT.getScalarSizeInBits(); 7688 7689 switch (Op.getOpcode()) { 7690 default: 7691 llvm_unreachable("unexpected shift opcode"); 7692 7693 case ISD::SHL: 7694 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) 7695 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0), 7696 DAG.getConstant(Cnt, DL, MVT::i32)); 7697 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 7698 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL, 7699 MVT::i32), 7700 Op.getOperand(0), Op.getOperand(1)); 7701 case ISD::SRA: 7702 case ISD::SRL: 7703 // Right shift immediate 7704 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) { 7705 unsigned Opc = 7706 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR; 7707 return DAG.getNode(Opc, DL, VT, Op.getOperand(0), 7708 DAG.getConstant(Cnt, DL, MVT::i32)); 7709 } 7710 7711 // Right shift register. Note, there is not a shift right register 7712 // instruction, but the shift left register instruction takes a signed 7713 // value, where negative numbers specify a right shift. 7714 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl 7715 : Intrinsic::aarch64_neon_ushl; 7716 // negate the shift amount 7717 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1)); 7718 SDValue NegShiftLeft = 7719 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT, 7720 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0), 7721 NegShift); 7722 return NegShiftLeft; 7723 } 7724 7725 return SDValue(); 7726 } 7727 7728 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS, 7729 AArch64CC::CondCode CC, bool NoNans, EVT VT, 7730 const SDLoc &dl, SelectionDAG &DAG) { 7731 EVT SrcVT = LHS.getValueType(); 7732 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() && 7733 "function only supposed to emit natural comparisons"); 7734 7735 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode()); 7736 APInt CnstBits(VT.getSizeInBits(), 0); 7737 APInt UndefBits(VT.getSizeInBits(), 0); 7738 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits); 7739 bool IsZero = IsCnst && (CnstBits == 0); 7740 7741 if (SrcVT.getVectorElementType().isFloatingPoint()) { 7742 switch (CC) { 7743 default: 7744 return SDValue(); 7745 case AArch64CC::NE: { 7746 SDValue Fcmeq; 7747 if (IsZero) 7748 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 7749 else 7750 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 7751 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq); 7752 } 7753 case AArch64CC::EQ: 7754 if (IsZero) 7755 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS); 7756 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS); 7757 case AArch64CC::GE: 7758 if (IsZero) 7759 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS); 7760 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS); 7761 case AArch64CC::GT: 7762 if (IsZero) 7763 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS); 7764 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS); 7765 case AArch64CC::LS: 7766 if (IsZero) 7767 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS); 7768 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS); 7769 case AArch64CC::LT: 7770 if (!NoNans) 7771 return SDValue(); 7772 // If we ignore NaNs then we can use to the MI implementation. 7773 LLVM_FALLTHROUGH; 7774 case AArch64CC::MI: 7775 if (IsZero) 7776 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS); 7777 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS); 7778 } 7779 } 7780 7781 switch (CC) { 7782 default: 7783 return SDValue(); 7784 case AArch64CC::NE: { 7785 SDValue Cmeq; 7786 if (IsZero) 7787 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 7788 else 7789 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 7790 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq); 7791 } 7792 case AArch64CC::EQ: 7793 if (IsZero) 7794 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS); 7795 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS); 7796 case AArch64CC::GE: 7797 if (IsZero) 7798 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS); 7799 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS); 7800 case AArch64CC::GT: 7801 if (IsZero) 7802 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS); 7803 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS); 7804 case AArch64CC::LE: 7805 if (IsZero) 7806 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS); 7807 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS); 7808 case AArch64CC::LS: 7809 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS); 7810 case AArch64CC::LO: 7811 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS); 7812 case AArch64CC::LT: 7813 if (IsZero) 7814 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS); 7815 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS); 7816 case AArch64CC::HI: 7817 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS); 7818 case AArch64CC::HS: 7819 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS); 7820 } 7821 } 7822 7823 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op, 7824 SelectionDAG &DAG) const { 7825 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 7826 SDValue LHS = Op.getOperand(0); 7827 SDValue RHS = Op.getOperand(1); 7828 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger(); 7829 SDLoc dl(Op); 7830 7831 if (LHS.getValueType().getVectorElementType().isInteger()) { 7832 assert(LHS.getValueType() == RHS.getValueType()); 7833 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC); 7834 SDValue Cmp = 7835 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG); 7836 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 7837 } 7838 7839 const bool FullFP16 = 7840 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16(); 7841 7842 // Make v4f16 (only) fcmp operations utilise vector instructions 7843 // v8f16 support will be a litle more complicated 7844 if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) { 7845 if (LHS.getValueType().getVectorNumElements() == 4) { 7846 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS); 7847 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS); 7848 SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC); 7849 DAG.ReplaceAllUsesWith(Op, NewSetcc); 7850 CmpVT = MVT::v4i32; 7851 } else 7852 return SDValue(); 7853 } 7854 7855 assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) || 7856 LHS.getValueType().getVectorElementType() != MVT::f128); 7857 7858 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally 7859 // clean. Some of them require two branches to implement. 7860 AArch64CC::CondCode CC1, CC2; 7861 bool ShouldInvert; 7862 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert); 7863 7864 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath; 7865 SDValue Cmp = 7866 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG); 7867 if (!Cmp.getNode()) 7868 return SDValue(); 7869 7870 if (CC2 != AArch64CC::AL) { 7871 SDValue Cmp2 = 7872 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG); 7873 if (!Cmp2.getNode()) 7874 return SDValue(); 7875 7876 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2); 7877 } 7878 7879 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType()); 7880 7881 if (ShouldInvert) 7882 Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType()); 7883 7884 return Cmp; 7885 } 7886 7887 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp, 7888 SelectionDAG &DAG) { 7889 SDValue VecOp = ScalarOp.getOperand(0); 7890 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp); 7891 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx, 7892 DAG.getConstant(0, DL, MVT::i64)); 7893 } 7894 7895 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op, 7896 SelectionDAG &DAG) const { 7897 SDLoc dl(Op); 7898 switch (Op.getOpcode()) { 7899 case ISD::VECREDUCE_ADD: 7900 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG); 7901 case ISD::VECREDUCE_SMAX: 7902 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG); 7903 case ISD::VECREDUCE_SMIN: 7904 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG); 7905 case ISD::VECREDUCE_UMAX: 7906 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG); 7907 case ISD::VECREDUCE_UMIN: 7908 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG); 7909 case ISD::VECREDUCE_FMAX: { 7910 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag"); 7911 return DAG.getNode( 7912 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), 7913 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32), 7914 Op.getOperand(0)); 7915 } 7916 case ISD::VECREDUCE_FMIN: { 7917 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag"); 7918 return DAG.getNode( 7919 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), 7920 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32), 7921 Op.getOperand(0)); 7922 } 7923 default: 7924 llvm_unreachable("Unhandled reduction"); 7925 } 7926 } 7927 7928 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op, 7929 SelectionDAG &DAG) const { 7930 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget()); 7931 if (!Subtarget.hasLSE()) 7932 return SDValue(); 7933 7934 // LSE has an atomic load-add instruction, but not a load-sub. 7935 SDLoc dl(Op); 7936 MVT VT = Op.getSimpleValueType(); 7937 SDValue RHS = Op.getOperand(2); 7938 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode()); 7939 RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS); 7940 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(), 7941 Op.getOperand(0), Op.getOperand(1), RHS, 7942 AN->getMemOperand()); 7943 } 7944 7945 SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op, 7946 SelectionDAG &DAG) const { 7947 auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget()); 7948 if (!Subtarget.hasLSE()) 7949 return SDValue(); 7950 7951 // LSE has an atomic load-clear instruction, but not a load-and. 7952 SDLoc dl(Op); 7953 MVT VT = Op.getSimpleValueType(); 7954 SDValue RHS = Op.getOperand(2); 7955 AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode()); 7956 RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS); 7957 return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(), 7958 Op.getOperand(0), Op.getOperand(1), RHS, 7959 AN->getMemOperand()); 7960 } 7961 7962 SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC( 7963 SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const { 7964 SDLoc dl(Op); 7965 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 7966 SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0); 7967 7968 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 7969 const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask(); 7970 if (Subtarget->hasCustomCallingConv()) 7971 TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask); 7972 7973 Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size, 7974 DAG.getConstant(4, dl, MVT::i64)); 7975 Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue()); 7976 Chain = 7977 DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue), 7978 Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64), 7979 DAG.getRegisterMask(Mask), Chain.getValue(1)); 7980 // To match the actual intent better, we should read the output from X15 here 7981 // again (instead of potentially spilling it to the stack), but rereading Size 7982 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined 7983 // here. 7984 7985 Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size, 7986 DAG.getConstant(4, dl, MVT::i64)); 7987 return Chain; 7988 } 7989 7990 SDValue 7991 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, 7992 SelectionDAG &DAG) const { 7993 assert(Subtarget->isTargetWindows() && 7994 "Only Windows alloca probing supported"); 7995 SDLoc dl(Op); 7996 // Get the inputs. 7997 SDNode *Node = Op.getNode(); 7998 SDValue Chain = Op.getOperand(0); 7999 SDValue Size = Op.getOperand(1); 8000 unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue(); 8001 EVT VT = Node->getValueType(0); 8002 8003 if (DAG.getMachineFunction().getFunction().hasFnAttribute( 8004 "no-stack-arg-probe")) { 8005 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64); 8006 Chain = SP.getValue(1); 8007 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size); 8008 if (Align) 8009 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0), 8010 DAG.getConstant(-(uint64_t)Align, dl, VT)); 8011 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP); 8012 SDValue Ops[2] = {SP, Chain}; 8013 return DAG.getMergeValues(Ops, dl); 8014 } 8015 8016 Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl); 8017 8018 Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG); 8019 8020 SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64); 8021 Chain = SP.getValue(1); 8022 SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size); 8023 if (Align) 8024 SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0), 8025 DAG.getConstant(-(uint64_t)Align, dl, VT)); 8026 Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP); 8027 8028 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true), 8029 DAG.getIntPtrConstant(0, dl, true), SDValue(), dl); 8030 8031 SDValue Ops[2] = {SP, Chain}; 8032 return DAG.getMergeValues(Ops, dl); 8033 } 8034 8035 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as 8036 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment 8037 /// specified in the intrinsic calls. 8038 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 8039 const CallInst &I, 8040 MachineFunction &MF, 8041 unsigned Intrinsic) const { 8042 auto &DL = I.getModule()->getDataLayout(); 8043 switch (Intrinsic) { 8044 case Intrinsic::aarch64_neon_ld2: 8045 case Intrinsic::aarch64_neon_ld3: 8046 case Intrinsic::aarch64_neon_ld4: 8047 case Intrinsic::aarch64_neon_ld1x2: 8048 case Intrinsic::aarch64_neon_ld1x3: 8049 case Intrinsic::aarch64_neon_ld1x4: 8050 case Intrinsic::aarch64_neon_ld2lane: 8051 case Intrinsic::aarch64_neon_ld3lane: 8052 case Intrinsic::aarch64_neon_ld4lane: 8053 case Intrinsic::aarch64_neon_ld2r: 8054 case Intrinsic::aarch64_neon_ld3r: 8055 case Intrinsic::aarch64_neon_ld4r: { 8056 Info.opc = ISD::INTRINSIC_W_CHAIN; 8057 // Conservatively set memVT to the entire set of vectors loaded. 8058 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64; 8059 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 8060 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 8061 Info.offset = 0; 8062 Info.align = 0; 8063 // volatile loads with NEON intrinsics not supported 8064 Info.flags = MachineMemOperand::MOLoad; 8065 return true; 8066 } 8067 case Intrinsic::aarch64_neon_st2: 8068 case Intrinsic::aarch64_neon_st3: 8069 case Intrinsic::aarch64_neon_st4: 8070 case Intrinsic::aarch64_neon_st1x2: 8071 case Intrinsic::aarch64_neon_st1x3: 8072 case Intrinsic::aarch64_neon_st1x4: 8073 case Intrinsic::aarch64_neon_st2lane: 8074 case Intrinsic::aarch64_neon_st3lane: 8075 case Intrinsic::aarch64_neon_st4lane: { 8076 Info.opc = ISD::INTRINSIC_VOID; 8077 // Conservatively set memVT to the entire set of vectors stored. 8078 unsigned NumElts = 0; 8079 for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) { 8080 Type *ArgTy = I.getArgOperand(ArgI)->getType(); 8081 if (!ArgTy->isVectorTy()) 8082 break; 8083 NumElts += DL.getTypeSizeInBits(ArgTy) / 64; 8084 } 8085 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts); 8086 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1); 8087 Info.offset = 0; 8088 Info.align = 0; 8089 // volatile stores with NEON intrinsics not supported 8090 Info.flags = MachineMemOperand::MOStore; 8091 return true; 8092 } 8093 case Intrinsic::aarch64_ldaxr: 8094 case Intrinsic::aarch64_ldxr: { 8095 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType()); 8096 Info.opc = ISD::INTRINSIC_W_CHAIN; 8097 Info.memVT = MVT::getVT(PtrTy->getElementType()); 8098 Info.ptrVal = I.getArgOperand(0); 8099 Info.offset = 0; 8100 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 8101 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 8102 return true; 8103 } 8104 case Intrinsic::aarch64_stlxr: 8105 case Intrinsic::aarch64_stxr: { 8106 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType()); 8107 Info.opc = ISD::INTRINSIC_W_CHAIN; 8108 Info.memVT = MVT::getVT(PtrTy->getElementType()); 8109 Info.ptrVal = I.getArgOperand(1); 8110 Info.offset = 0; 8111 Info.align = DL.getABITypeAlignment(PtrTy->getElementType()); 8112 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 8113 return true; 8114 } 8115 case Intrinsic::aarch64_ldaxp: 8116 case Intrinsic::aarch64_ldxp: 8117 Info.opc = ISD::INTRINSIC_W_CHAIN; 8118 Info.memVT = MVT::i128; 8119 Info.ptrVal = I.getArgOperand(0); 8120 Info.offset = 0; 8121 Info.align = 16; 8122 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile; 8123 return true; 8124 case Intrinsic::aarch64_stlxp: 8125 case Intrinsic::aarch64_stxp: 8126 Info.opc = ISD::INTRINSIC_W_CHAIN; 8127 Info.memVT = MVT::i128; 8128 Info.ptrVal = I.getArgOperand(2); 8129 Info.offset = 0; 8130 Info.align = 16; 8131 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile; 8132 return true; 8133 default: 8134 break; 8135 } 8136 8137 return false; 8138 } 8139 8140 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load, 8141 ISD::LoadExtType ExtTy, 8142 EVT NewVT) const { 8143 // TODO: This may be worth removing. Check regression tests for diffs. 8144 if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT)) 8145 return false; 8146 8147 // If we're reducing the load width in order to avoid having to use an extra 8148 // instruction to do extension then it's probably a good idea. 8149 if (ExtTy != ISD::NON_EXTLOAD) 8150 return true; 8151 // Don't reduce load width if it would prevent us from combining a shift into 8152 // the offset. 8153 MemSDNode *Mem = dyn_cast<MemSDNode>(Load); 8154 assert(Mem); 8155 const SDValue &Base = Mem->getBasePtr(); 8156 if (Base.getOpcode() == ISD::ADD && 8157 Base.getOperand(1).getOpcode() == ISD::SHL && 8158 Base.getOperand(1).hasOneUse() && 8159 Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) { 8160 // The shift can be combined if it matches the size of the value being 8161 // loaded (and so reducing the width would make it not match). 8162 uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1); 8163 uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8; 8164 if (ShiftAmount == Log2_32(LoadBytes)) 8165 return false; 8166 } 8167 // We have no reason to disallow reducing the load width, so allow it. 8168 return true; 8169 } 8170 8171 // Truncations from 64-bit GPR to 32-bit GPR is free. 8172 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const { 8173 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 8174 return false; 8175 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 8176 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 8177 return NumBits1 > NumBits2; 8178 } 8179 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const { 8180 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 8181 return false; 8182 unsigned NumBits1 = VT1.getSizeInBits(); 8183 unsigned NumBits2 = VT2.getSizeInBits(); 8184 return NumBits1 > NumBits2; 8185 } 8186 8187 /// Check if it is profitable to hoist instruction in then/else to if. 8188 /// Not profitable if I and it's user can form a FMA instruction 8189 /// because we prefer FMSUB/FMADD. 8190 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const { 8191 if (I->getOpcode() != Instruction::FMul) 8192 return true; 8193 8194 if (!I->hasOneUse()) 8195 return true; 8196 8197 Instruction *User = I->user_back(); 8198 8199 if (User && 8200 !(User->getOpcode() == Instruction::FSub || 8201 User->getOpcode() == Instruction::FAdd)) 8202 return true; 8203 8204 const TargetOptions &Options = getTargetMachine().Options; 8205 const DataLayout &DL = I->getModule()->getDataLayout(); 8206 EVT VT = getValueType(DL, User->getOperand(0)->getType()); 8207 8208 return !(isFMAFasterThanFMulAndFAdd(VT) && 8209 isOperationLegalOrCustom(ISD::FMA, VT) && 8210 (Options.AllowFPOpFusion == FPOpFusion::Fast || 8211 Options.UnsafeFPMath)); 8212 } 8213 8214 // All 32-bit GPR operations implicitly zero the high-half of the corresponding 8215 // 64-bit GPR. 8216 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const { 8217 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy()) 8218 return false; 8219 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits(); 8220 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits(); 8221 return NumBits1 == 32 && NumBits2 == 64; 8222 } 8223 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const { 8224 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger()) 8225 return false; 8226 unsigned NumBits1 = VT1.getSizeInBits(); 8227 unsigned NumBits2 = VT2.getSizeInBits(); 8228 return NumBits1 == 32 && NumBits2 == 64; 8229 } 8230 8231 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 8232 EVT VT1 = Val.getValueType(); 8233 if (isZExtFree(VT1, VT2)) { 8234 return true; 8235 } 8236 8237 if (Val.getOpcode() != ISD::LOAD) 8238 return false; 8239 8240 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend. 8241 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() && 8242 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() && 8243 VT1.getSizeInBits() <= 32); 8244 } 8245 8246 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const { 8247 if (isa<FPExtInst>(Ext)) 8248 return false; 8249 8250 // Vector types are not free. 8251 if (Ext->getType()->isVectorTy()) 8252 return false; 8253 8254 for (const Use &U : Ext->uses()) { 8255 // The extension is free if we can fold it with a left shift in an 8256 // addressing mode or an arithmetic operation: add, sub, and cmp. 8257 8258 // Is there a shift? 8259 const Instruction *Instr = cast<Instruction>(U.getUser()); 8260 8261 // Is this a constant shift? 8262 switch (Instr->getOpcode()) { 8263 case Instruction::Shl: 8264 if (!isa<ConstantInt>(Instr->getOperand(1))) 8265 return false; 8266 break; 8267 case Instruction::GetElementPtr: { 8268 gep_type_iterator GTI = gep_type_begin(Instr); 8269 auto &DL = Ext->getModule()->getDataLayout(); 8270 std::advance(GTI, U.getOperandNo()-1); 8271 Type *IdxTy = GTI.getIndexedType(); 8272 // This extension will end up with a shift because of the scaling factor. 8273 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0. 8274 // Get the shift amount based on the scaling factor: 8275 // log2(sizeof(IdxTy)) - log2(8). 8276 uint64_t ShiftAmt = 8277 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3; 8278 // Is the constant foldable in the shift of the addressing mode? 8279 // I.e., shift amount is between 1 and 4 inclusive. 8280 if (ShiftAmt == 0 || ShiftAmt > 4) 8281 return false; 8282 break; 8283 } 8284 case Instruction::Trunc: 8285 // Check if this is a noop. 8286 // trunc(sext ty1 to ty2) to ty1. 8287 if (Instr->getType() == Ext->getOperand(0)->getType()) 8288 continue; 8289 LLVM_FALLTHROUGH; 8290 default: 8291 return false; 8292 } 8293 8294 // At this point we can use the bfm family, so this extension is free 8295 // for that use. 8296 } 8297 return true; 8298 } 8299 8300 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower 8301 /// or upper half of the vector elements. 8302 static bool areExtractShuffleVectors(Value *Op1, Value *Op2) { 8303 auto areTypesHalfed = [](Value *FullV, Value *HalfV) { 8304 auto *FullVT = cast<VectorType>(FullV->getType()); 8305 auto *HalfVT = cast<VectorType>(HalfV->getType()); 8306 return FullVT->getBitWidth() == 2 * HalfVT->getBitWidth(); 8307 }; 8308 8309 auto extractHalf = [](Value *FullV, Value *HalfV) { 8310 auto *FullVT = cast<VectorType>(FullV->getType()); 8311 auto *HalfVT = cast<VectorType>(HalfV->getType()); 8312 return FullVT->getNumElements() == 2 * HalfVT->getNumElements(); 8313 }; 8314 8315 Constant *M1, *M2; 8316 Value *S1Op1, *S2Op1; 8317 if (!match(Op1, m_ShuffleVector(m_Value(S1Op1), m_Undef(), m_Constant(M1))) || 8318 !match(Op2, m_ShuffleVector(m_Value(S2Op1), m_Undef(), m_Constant(M2)))) 8319 return false; 8320 8321 // Check that the operands are half as wide as the result and we extract 8322 // half of the elements of the input vectors. 8323 if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) || 8324 !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2)) 8325 return false; 8326 8327 // Check the mask extracts either the lower or upper half of vector 8328 // elements. 8329 int M1Start = -1; 8330 int M2Start = -1; 8331 int NumElements = cast<VectorType>(Op1->getType())->getNumElements() * 2; 8332 if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) || 8333 !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) || 8334 M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2))) 8335 return false; 8336 8337 return true; 8338 } 8339 8340 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth 8341 /// of the vector elements. 8342 static bool areExtractExts(Value *Ext1, Value *Ext2) { 8343 auto areExtDoubled = [](Instruction *Ext) { 8344 return Ext->getType()->getScalarSizeInBits() == 8345 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits(); 8346 }; 8347 8348 if (!match(Ext1, m_ZExtOrSExt(m_Value())) || 8349 !match(Ext2, m_ZExtOrSExt(m_Value())) || 8350 !areExtDoubled(cast<Instruction>(Ext1)) || 8351 !areExtDoubled(cast<Instruction>(Ext2))) 8352 return false; 8353 8354 return true; 8355 } 8356 8357 /// Check if sinking \p I's operands to I's basic block is profitable, because 8358 /// the operands can be folded into a target instruction, e.g. 8359 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2). 8360 bool AArch64TargetLowering::shouldSinkOperands( 8361 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 8362 if (!I->getType()->isVectorTy()) 8363 return false; 8364 8365 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 8366 switch (II->getIntrinsicID()) { 8367 case Intrinsic::aarch64_neon_umull: 8368 if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1))) 8369 return false; 8370 Ops.push_back(&II->getOperandUse(0)); 8371 Ops.push_back(&II->getOperandUse(1)); 8372 return true; 8373 default: 8374 return false; 8375 } 8376 } 8377 8378 switch (I->getOpcode()) { 8379 case Instruction::Sub: 8380 case Instruction::Add: { 8381 if (!areExtractExts(I->getOperand(0), I->getOperand(1))) 8382 return false; 8383 8384 // If the exts' operands extract either the lower or upper elements, we 8385 // can sink them too. 8386 auto Ext1 = cast<Instruction>(I->getOperand(0)); 8387 auto Ext2 = cast<Instruction>(I->getOperand(1)); 8388 if (areExtractShuffleVectors(Ext1, Ext2)) { 8389 Ops.push_back(&Ext1->getOperandUse(0)); 8390 Ops.push_back(&Ext2->getOperandUse(0)); 8391 } 8392 8393 Ops.push_back(&I->getOperandUse(0)); 8394 Ops.push_back(&I->getOperandUse(1)); 8395 8396 return true; 8397 } 8398 default: 8399 return false; 8400 } 8401 return false; 8402 } 8403 8404 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType, 8405 unsigned &RequiredAligment) const { 8406 if (!LoadedType.isSimple() || 8407 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint())) 8408 return false; 8409 // Cyclone supports unaligned accesses. 8410 RequiredAligment = 0; 8411 unsigned NumBits = LoadedType.getSizeInBits(); 8412 return NumBits == 32 || NumBits == 64; 8413 } 8414 8415 /// A helper function for determining the number of interleaved accesses we 8416 /// will generate when lowering accesses of the given type. 8417 unsigned 8418 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy, 8419 const DataLayout &DL) const { 8420 return (DL.getTypeSizeInBits(VecTy) + 127) / 128; 8421 } 8422 8423 MachineMemOperand::Flags 8424 AArch64TargetLowering::getMMOFlags(const Instruction &I) const { 8425 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor && 8426 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr) 8427 return MOStridedAccess; 8428 return MachineMemOperand::MONone; 8429 } 8430 8431 bool AArch64TargetLowering::isLegalInterleavedAccessType( 8432 VectorType *VecTy, const DataLayout &DL) const { 8433 8434 unsigned VecSize = DL.getTypeSizeInBits(VecTy); 8435 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType()); 8436 8437 // Ensure the number of vector elements is greater than 1. 8438 if (VecTy->getNumElements() < 2) 8439 return false; 8440 8441 // Ensure the element type is legal. 8442 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64) 8443 return false; 8444 8445 // Ensure the total vector size is 64 or a multiple of 128. Types larger than 8446 // 128 will be split into multiple interleaved accesses. 8447 return VecSize == 64 || VecSize % 128 == 0; 8448 } 8449 8450 /// Lower an interleaved load into a ldN intrinsic. 8451 /// 8452 /// E.g. Lower an interleaved load (Factor = 2): 8453 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr 8454 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements 8455 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements 8456 /// 8457 /// Into: 8458 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr) 8459 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0 8460 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1 8461 bool AArch64TargetLowering::lowerInterleavedLoad( 8462 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles, 8463 ArrayRef<unsigned> Indices, unsigned Factor) const { 8464 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 8465 "Invalid interleave factor"); 8466 assert(!Shuffles.empty() && "Empty shufflevector input"); 8467 assert(Shuffles.size() == Indices.size() && 8468 "Unmatched number of shufflevectors and indices"); 8469 8470 const DataLayout &DL = LI->getModule()->getDataLayout(); 8471 8472 VectorType *VecTy = Shuffles[0]->getType(); 8473 8474 // Skip if we do not have NEON and skip illegal vector types. We can 8475 // "legalize" wide vector types into multiple interleaved accesses as long as 8476 // the vector types are divisible by 128. 8477 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL)) 8478 return false; 8479 8480 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL); 8481 8482 // A pointer vector can not be the return type of the ldN intrinsics. Need to 8483 // load integer vectors first and then convert to pointer vectors. 8484 Type *EltTy = VecTy->getVectorElementType(); 8485 if (EltTy->isPointerTy()) 8486 VecTy = 8487 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements()); 8488 8489 IRBuilder<> Builder(LI); 8490 8491 // The base address of the load. 8492 Value *BaseAddr = LI->getPointerOperand(); 8493 8494 if (NumLoads > 1) { 8495 // If we're going to generate more than one load, reset the sub-vector type 8496 // to something legal. 8497 VecTy = VectorType::get(VecTy->getVectorElementType(), 8498 VecTy->getVectorNumElements() / NumLoads); 8499 8500 // We will compute the pointer operand of each load from the original base 8501 // address using GEPs. Cast the base address to a pointer to the scalar 8502 // element type. 8503 BaseAddr = Builder.CreateBitCast( 8504 BaseAddr, VecTy->getVectorElementType()->getPointerTo( 8505 LI->getPointerAddressSpace())); 8506 } 8507 8508 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace()); 8509 Type *Tys[2] = {VecTy, PtrTy}; 8510 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2, 8511 Intrinsic::aarch64_neon_ld3, 8512 Intrinsic::aarch64_neon_ld4}; 8513 Function *LdNFunc = 8514 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys); 8515 8516 // Holds sub-vectors extracted from the load intrinsic return values. The 8517 // sub-vectors are associated with the shufflevector instructions they will 8518 // replace. 8519 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs; 8520 8521 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) { 8522 8523 // If we're generating more than one load, compute the base address of 8524 // subsequent loads as an offset from the previous. 8525 if (LoadCount > 0) 8526 BaseAddr = 8527 Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr, 8528 VecTy->getVectorNumElements() * Factor); 8529 8530 CallInst *LdN = Builder.CreateCall( 8531 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN"); 8532 8533 // Extract and store the sub-vectors returned by the load intrinsic. 8534 for (unsigned i = 0; i < Shuffles.size(); i++) { 8535 ShuffleVectorInst *SVI = Shuffles[i]; 8536 unsigned Index = Indices[i]; 8537 8538 Value *SubVec = Builder.CreateExtractValue(LdN, Index); 8539 8540 // Convert the integer vector to pointer vector if the element is pointer. 8541 if (EltTy->isPointerTy()) 8542 SubVec = Builder.CreateIntToPtr( 8543 SubVec, VectorType::get(SVI->getType()->getVectorElementType(), 8544 VecTy->getVectorNumElements())); 8545 SubVecs[SVI].push_back(SubVec); 8546 } 8547 } 8548 8549 // Replace uses of the shufflevector instructions with the sub-vectors 8550 // returned by the load intrinsic. If a shufflevector instruction is 8551 // associated with more than one sub-vector, those sub-vectors will be 8552 // concatenated into a single wide vector. 8553 for (ShuffleVectorInst *SVI : Shuffles) { 8554 auto &SubVec = SubVecs[SVI]; 8555 auto *WideVec = 8556 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0]; 8557 SVI->replaceAllUsesWith(WideVec); 8558 } 8559 8560 return true; 8561 } 8562 8563 /// Lower an interleaved store into a stN intrinsic. 8564 /// 8565 /// E.g. Lower an interleaved store (Factor = 3): 8566 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1, 8567 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> 8568 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 8569 /// 8570 /// Into: 8571 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3> 8572 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7> 8573 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11> 8574 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 8575 /// 8576 /// Note that the new shufflevectors will be removed and we'll only generate one 8577 /// st3 instruction in CodeGen. 8578 /// 8579 /// Example for a more general valid mask (Factor 3). Lower: 8580 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1, 8581 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19> 8582 /// store <12 x i32> %i.vec, <12 x i32>* %ptr 8583 /// 8584 /// Into: 8585 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7> 8586 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35> 8587 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19> 8588 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr) 8589 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI, 8590 ShuffleVectorInst *SVI, 8591 unsigned Factor) const { 8592 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && 8593 "Invalid interleave factor"); 8594 8595 VectorType *VecTy = SVI->getType(); 8596 assert(VecTy->getVectorNumElements() % Factor == 0 && 8597 "Invalid interleaved store"); 8598 8599 unsigned LaneLen = VecTy->getVectorNumElements() / Factor; 8600 Type *EltTy = VecTy->getVectorElementType(); 8601 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen); 8602 8603 const DataLayout &DL = SI->getModule()->getDataLayout(); 8604 8605 // Skip if we do not have NEON and skip illegal vector types. We can 8606 // "legalize" wide vector types into multiple interleaved accesses as long as 8607 // the vector types are divisible by 128. 8608 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL)) 8609 return false; 8610 8611 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL); 8612 8613 Value *Op0 = SVI->getOperand(0); 8614 Value *Op1 = SVI->getOperand(1); 8615 IRBuilder<> Builder(SI); 8616 8617 // StN intrinsics don't support pointer vectors as arguments. Convert pointer 8618 // vectors to integer vectors. 8619 if (EltTy->isPointerTy()) { 8620 Type *IntTy = DL.getIntPtrType(EltTy); 8621 unsigned NumOpElts = Op0->getType()->getVectorNumElements(); 8622 8623 // Convert to the corresponding integer vector. 8624 Type *IntVecTy = VectorType::get(IntTy, NumOpElts); 8625 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy); 8626 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy); 8627 8628 SubVecTy = VectorType::get(IntTy, LaneLen); 8629 } 8630 8631 // The base address of the store. 8632 Value *BaseAddr = SI->getPointerOperand(); 8633 8634 if (NumStores > 1) { 8635 // If we're going to generate more than one store, reset the lane length 8636 // and sub-vector type to something legal. 8637 LaneLen /= NumStores; 8638 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen); 8639 8640 // We will compute the pointer operand of each store from the original base 8641 // address using GEPs. Cast the base address to a pointer to the scalar 8642 // element type. 8643 BaseAddr = Builder.CreateBitCast( 8644 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo( 8645 SI->getPointerAddressSpace())); 8646 } 8647 8648 auto Mask = SVI->getShuffleMask(); 8649 8650 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace()); 8651 Type *Tys[2] = {SubVecTy, PtrTy}; 8652 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2, 8653 Intrinsic::aarch64_neon_st3, 8654 Intrinsic::aarch64_neon_st4}; 8655 Function *StNFunc = 8656 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys); 8657 8658 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) { 8659 8660 SmallVector<Value *, 5> Ops; 8661 8662 // Split the shufflevector operands into sub vectors for the new stN call. 8663 for (unsigned i = 0; i < Factor; i++) { 8664 unsigned IdxI = StoreCount * LaneLen * Factor + i; 8665 if (Mask[IdxI] >= 0) { 8666 Ops.push_back(Builder.CreateShuffleVector( 8667 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0))); 8668 } else { 8669 unsigned StartMask = 0; 8670 for (unsigned j = 1; j < LaneLen; j++) { 8671 unsigned IdxJ = StoreCount * LaneLen * Factor + j; 8672 if (Mask[IdxJ * Factor + IdxI] >= 0) { 8673 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ; 8674 break; 8675 } 8676 } 8677 // Note: Filling undef gaps with random elements is ok, since 8678 // those elements were being written anyway (with undefs). 8679 // In the case of all undefs we're defaulting to using elems from 0 8680 // Note: StartMask cannot be negative, it's checked in 8681 // isReInterleaveMask 8682 Ops.push_back(Builder.CreateShuffleVector( 8683 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0))); 8684 } 8685 } 8686 8687 // If we generating more than one store, we compute the base address of 8688 // subsequent stores as an offset from the previous. 8689 if (StoreCount > 0) 8690 BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(), 8691 BaseAddr, LaneLen * Factor); 8692 8693 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy)); 8694 Builder.CreateCall(StNFunc, Ops); 8695 } 8696 return true; 8697 } 8698 8699 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign, 8700 unsigned AlignCheck) { 8701 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) && 8702 (DstAlign == 0 || DstAlign % AlignCheck == 0)); 8703 } 8704 8705 EVT AArch64TargetLowering::getOptimalMemOpType( 8706 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset, 8707 bool ZeroMemset, bool MemcpyStrSrc, 8708 const AttributeList &FuncAttributes) const { 8709 bool CanImplicitFloat = 8710 !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat); 8711 bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat; 8712 bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat; 8713 // Only use AdvSIMD to implement memset of 32-byte and above. It would have 8714 // taken one instruction to materialize the v2i64 zero and one store (with 8715 // restrictive addressing mode). Just do i64 stores. 8716 bool IsSmallMemset = IsMemset && Size < 32; 8717 auto AlignmentIsAcceptable = [&](EVT VT, unsigned AlignCheck) { 8718 if (memOpAlign(SrcAlign, DstAlign, AlignCheck)) 8719 return true; 8720 bool Fast; 8721 return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone, 8722 &Fast) && 8723 Fast; 8724 }; 8725 8726 if (CanUseNEON && IsMemset && !IsSmallMemset && 8727 AlignmentIsAcceptable(MVT::v2i64, 16)) 8728 return MVT::v2i64; 8729 if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, 16)) 8730 return MVT::f128; 8731 if (Size >= 8 && AlignmentIsAcceptable(MVT::i64, 8)) 8732 return MVT::i64; 8733 if (Size >= 4 && AlignmentIsAcceptable(MVT::i32, 4)) 8734 return MVT::i32; 8735 return MVT::Other; 8736 } 8737 8738 // 12-bit optionally shifted immediates are legal for adds. 8739 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const { 8740 if (Immed == std::numeric_limits<int64_t>::min()) { 8741 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed 8742 << ": avoid UB for INT64_MIN\n"); 8743 return false; 8744 } 8745 // Same encoding for add/sub, just flip the sign. 8746 Immed = std::abs(Immed); 8747 bool IsLegal = ((Immed >> 12) == 0 || 8748 ((Immed & 0xfff) == 0 && Immed >> 24 == 0)); 8749 LLVM_DEBUG(dbgs() << "Is " << Immed 8750 << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n"); 8751 return IsLegal; 8752 } 8753 8754 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid 8755 // immediates is the same as for an add or a sub. 8756 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const { 8757 return isLegalAddImmediate(Immed); 8758 } 8759 8760 /// isLegalAddressingMode - Return true if the addressing mode represented 8761 /// by AM is legal for this target, for a load/store of the specified type. 8762 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL, 8763 const AddrMode &AM, Type *Ty, 8764 unsigned AS, Instruction *I) const { 8765 // AArch64 has five basic addressing modes: 8766 // reg 8767 // reg + 9-bit signed offset 8768 // reg + SIZE_IN_BYTES * 12-bit unsigned offset 8769 // reg1 + reg2 8770 // reg + SIZE_IN_BYTES * reg 8771 8772 // No global is ever allowed as a base. 8773 if (AM.BaseGV) 8774 return false; 8775 8776 // No reg+reg+imm addressing. 8777 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale) 8778 return false; 8779 8780 // check reg + imm case: 8781 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12 8782 uint64_t NumBytes = 0; 8783 if (Ty->isSized()) { 8784 uint64_t NumBits = DL.getTypeSizeInBits(Ty); 8785 NumBytes = NumBits / 8; 8786 if (!isPowerOf2_64(NumBits)) 8787 NumBytes = 0; 8788 } 8789 8790 if (!AM.Scale) { 8791 int64_t Offset = AM.BaseOffs; 8792 8793 // 9-bit signed offset 8794 if (isInt<9>(Offset)) 8795 return true; 8796 8797 // 12-bit unsigned offset 8798 unsigned shift = Log2_64(NumBytes); 8799 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 && 8800 // Must be a multiple of NumBytes (NumBytes is a power of 2) 8801 (Offset >> shift) << shift == Offset) 8802 return true; 8803 return false; 8804 } 8805 8806 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2 8807 8808 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes); 8809 } 8810 8811 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const { 8812 // Consider splitting large offset of struct or array. 8813 return true; 8814 } 8815 8816 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL, 8817 const AddrMode &AM, Type *Ty, 8818 unsigned AS) const { 8819 // Scaling factors are not free at all. 8820 // Operands | Rt Latency 8821 // ------------------------------------------- 8822 // Rt, [Xn, Xm] | 4 8823 // ------------------------------------------- 8824 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5 8825 // Rt, [Xn, Wm, <extend> #imm] | 8826 if (isLegalAddressingMode(DL, AM, Ty, AS)) 8827 // Scale represents reg2 * scale, thus account for 1 if 8828 // it is not equal to 0 or 1. 8829 return AM.Scale != 0 && AM.Scale != 1; 8830 return -1; 8831 } 8832 8833 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const { 8834 VT = VT.getScalarType(); 8835 8836 if (!VT.isSimple()) 8837 return false; 8838 8839 switch (VT.getSimpleVT().SimpleTy) { 8840 case MVT::f32: 8841 case MVT::f64: 8842 return true; 8843 default: 8844 break; 8845 } 8846 8847 return false; 8848 } 8849 8850 const MCPhysReg * 8851 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const { 8852 // LR is a callee-save register, but we must treat it as clobbered by any call 8853 // site. Hence we include LR in the scratch registers, which are in turn added 8854 // as implicit-defs for stackmaps and patchpoints. 8855 static const MCPhysReg ScratchRegs[] = { 8856 AArch64::X16, AArch64::X17, AArch64::LR, 0 8857 }; 8858 return ScratchRegs; 8859 } 8860 8861 bool 8862 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N, 8863 CombineLevel Level) const { 8864 N = N->getOperand(0).getNode(); 8865 EVT VT = N->getValueType(0); 8866 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine 8867 // it with shift to let it be lowered to UBFX. 8868 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) && 8869 isa<ConstantSDNode>(N->getOperand(1))) { 8870 uint64_t TruncMask = N->getConstantOperandVal(1); 8871 if (isMask_64(TruncMask) && 8872 N->getOperand(0).getOpcode() == ISD::SRL && 8873 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1))) 8874 return false; 8875 } 8876 return true; 8877 } 8878 8879 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 8880 Type *Ty) const { 8881 assert(Ty->isIntegerTy()); 8882 8883 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 8884 if (BitSize == 0) 8885 return false; 8886 8887 int64_t Val = Imm.getSExtValue(); 8888 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize)) 8889 return true; 8890 8891 if ((int64_t)Val < 0) 8892 Val = ~Val; 8893 if (BitSize == 32) 8894 Val &= (1LL << 32) - 1; 8895 8896 unsigned LZ = countLeadingZeros((uint64_t)Val); 8897 unsigned Shift = (63 - LZ) / 16; 8898 // MOVZ is free so return true for one or fewer MOVK. 8899 return Shift < 3; 8900 } 8901 8902 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT, 8903 unsigned Index) const { 8904 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT)) 8905 return false; 8906 8907 return (Index == 0 || Index == ResVT.getVectorNumElements()); 8908 } 8909 8910 /// Turn vector tests of the signbit in the form of: 8911 /// xor (sra X, elt_size(X)-1), -1 8912 /// into: 8913 /// cmge X, X, #0 8914 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG, 8915 const AArch64Subtarget *Subtarget) { 8916 EVT VT = N->getValueType(0); 8917 if (!Subtarget->hasNEON() || !VT.isVector()) 8918 return SDValue(); 8919 8920 // There must be a shift right algebraic before the xor, and the xor must be a 8921 // 'not' operation. 8922 SDValue Shift = N->getOperand(0); 8923 SDValue Ones = N->getOperand(1); 8924 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() || 8925 !ISD::isBuildVectorAllOnes(Ones.getNode())) 8926 return SDValue(); 8927 8928 // The shift should be smearing the sign bit across each vector element. 8929 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1)); 8930 EVT ShiftEltTy = Shift.getValueType().getVectorElementType(); 8931 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1) 8932 return SDValue(); 8933 8934 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0)); 8935 } 8936 8937 // Generate SUBS and CSEL for integer abs. 8938 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) { 8939 EVT VT = N->getValueType(0); 8940 8941 SDValue N0 = N->getOperand(0); 8942 SDValue N1 = N->getOperand(1); 8943 SDLoc DL(N); 8944 8945 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1) 8946 // and change it to SUB and CSEL. 8947 if (VT.isInteger() && N->getOpcode() == ISD::XOR && 8948 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 && 8949 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0)) 8950 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1))) 8951 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) { 8952 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), 8953 N0.getOperand(0)); 8954 // Generate SUBS & CSEL. 8955 SDValue Cmp = 8956 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32), 8957 N0.getOperand(0), DAG.getConstant(0, DL, VT)); 8958 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg, 8959 DAG.getConstant(AArch64CC::PL, DL, MVT::i32), 8960 SDValue(Cmp.getNode(), 1)); 8961 } 8962 return SDValue(); 8963 } 8964 8965 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG, 8966 TargetLowering::DAGCombinerInfo &DCI, 8967 const AArch64Subtarget *Subtarget) { 8968 if (DCI.isBeforeLegalizeOps()) 8969 return SDValue(); 8970 8971 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget)) 8972 return Cmp; 8973 8974 return performIntegerAbsCombine(N, DAG); 8975 } 8976 8977 SDValue 8978 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 8979 SelectionDAG &DAG, 8980 SmallVectorImpl<SDNode *> &Created) const { 8981 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 8982 if (isIntDivCheap(N->getValueType(0), Attr)) 8983 return SDValue(N,0); // Lower SDIV as SDIV 8984 8985 // fold (sdiv X, pow2) 8986 EVT VT = N->getValueType(0); 8987 if ((VT != MVT::i32 && VT != MVT::i64) || 8988 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2())) 8989 return SDValue(); 8990 8991 SDLoc DL(N); 8992 SDValue N0 = N->getOperand(0); 8993 unsigned Lg2 = Divisor.countTrailingZeros(); 8994 SDValue Zero = DAG.getConstant(0, DL, VT); 8995 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 8996 8997 // Add (N0 < 0) ? Pow2 - 1 : 0; 8998 SDValue CCVal; 8999 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL); 9000 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 9001 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp); 9002 9003 Created.push_back(Cmp.getNode()); 9004 Created.push_back(Add.getNode()); 9005 Created.push_back(CSel.getNode()); 9006 9007 // Divide by pow2. 9008 SDValue SRA = 9009 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64)); 9010 9011 // If we're dividing by a positive value, we're done. Otherwise, we must 9012 // negate the result. 9013 if (Divisor.isNonNegative()) 9014 return SRA; 9015 9016 Created.push_back(SRA.getNode()); 9017 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 9018 } 9019 9020 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG, 9021 TargetLowering::DAGCombinerInfo &DCI, 9022 const AArch64Subtarget *Subtarget) { 9023 if (DCI.isBeforeLegalizeOps()) 9024 return SDValue(); 9025 9026 // The below optimizations require a constant RHS. 9027 if (!isa<ConstantSDNode>(N->getOperand(1))) 9028 return SDValue(); 9029 9030 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1)); 9031 const APInt &ConstValue = C->getAPIntValue(); 9032 9033 // Multiplication of a power of two plus/minus one can be done more 9034 // cheaply as as shift+add/sub. For now, this is true unilaterally. If 9035 // future CPUs have a cheaper MADD instruction, this may need to be 9036 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and 9037 // 64-bit is 5 cycles, so this is always a win. 9038 // More aggressively, some multiplications N0 * C can be lowered to 9039 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M, 9040 // e.g. 6=3*2=(2+1)*2. 9041 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45 9042 // which equals to (1+2)*16-(1+2). 9043 SDValue N0 = N->getOperand(0); 9044 // TrailingZeroes is used to test if the mul can be lowered to 9045 // shift+add+shift. 9046 unsigned TrailingZeroes = ConstValue.countTrailingZeros(); 9047 if (TrailingZeroes) { 9048 // Conservatively do not lower to shift+add+shift if the mul might be 9049 // folded into smul or umul. 9050 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) || 9051 isZeroExtended(N0.getNode(), DAG))) 9052 return SDValue(); 9053 // Conservatively do not lower to shift+add+shift if the mul might be 9054 // folded into madd or msub. 9055 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD || 9056 N->use_begin()->getOpcode() == ISD::SUB)) 9057 return SDValue(); 9058 } 9059 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub 9060 // and shift+add+shift. 9061 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes); 9062 9063 unsigned ShiftAmt, AddSubOpc; 9064 // Is the shifted value the LHS operand of the add/sub? 9065 bool ShiftValUseIsN0 = true; 9066 // Do we need to negate the result? 9067 bool NegateResult = false; 9068 9069 if (ConstValue.isNonNegative()) { 9070 // (mul x, 2^N + 1) => (add (shl x, N), x) 9071 // (mul x, 2^N - 1) => (sub (shl x, N), x) 9072 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M) 9073 APInt SCVMinus1 = ShiftedConstValue - 1; 9074 APInt CVPlus1 = ConstValue + 1; 9075 if (SCVMinus1.isPowerOf2()) { 9076 ShiftAmt = SCVMinus1.logBase2(); 9077 AddSubOpc = ISD::ADD; 9078 } else if (CVPlus1.isPowerOf2()) { 9079 ShiftAmt = CVPlus1.logBase2(); 9080 AddSubOpc = ISD::SUB; 9081 } else 9082 return SDValue(); 9083 } else { 9084 // (mul x, -(2^N - 1)) => (sub x, (shl x, N)) 9085 // (mul x, -(2^N + 1)) => - (add (shl x, N), x) 9086 APInt CVNegPlus1 = -ConstValue + 1; 9087 APInt CVNegMinus1 = -ConstValue - 1; 9088 if (CVNegPlus1.isPowerOf2()) { 9089 ShiftAmt = CVNegPlus1.logBase2(); 9090 AddSubOpc = ISD::SUB; 9091 ShiftValUseIsN0 = false; 9092 } else if (CVNegMinus1.isPowerOf2()) { 9093 ShiftAmt = CVNegMinus1.logBase2(); 9094 AddSubOpc = ISD::ADD; 9095 NegateResult = true; 9096 } else 9097 return SDValue(); 9098 } 9099 9100 SDLoc DL(N); 9101 EVT VT = N->getValueType(0); 9102 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0, 9103 DAG.getConstant(ShiftAmt, DL, MVT::i64)); 9104 9105 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0; 9106 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal; 9107 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1); 9108 assert(!(NegateResult && TrailingZeroes) && 9109 "NegateResult and TrailingZeroes cannot both be true for now."); 9110 // Negate the result. 9111 if (NegateResult) 9112 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res); 9113 // Shift the result. 9114 if (TrailingZeroes) 9115 return DAG.getNode(ISD::SHL, DL, VT, Res, 9116 DAG.getConstant(TrailingZeroes, DL, MVT::i64)); 9117 return Res; 9118 } 9119 9120 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N, 9121 SelectionDAG &DAG) { 9122 // Take advantage of vector comparisons producing 0 or -1 in each lane to 9123 // optimize away operation when it's from a constant. 9124 // 9125 // The general transformation is: 9126 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) --> 9127 // AND(VECTOR_CMP(x,y), constant2) 9128 // constant2 = UNARYOP(constant) 9129 9130 // Early exit if this isn't a vector operation, the operand of the 9131 // unary operation isn't a bitwise AND, or if the sizes of the operations 9132 // aren't the same. 9133 EVT VT = N->getValueType(0); 9134 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND || 9135 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC || 9136 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits()) 9137 return SDValue(); 9138 9139 // Now check that the other operand of the AND is a constant. We could 9140 // make the transformation for non-constant splats as well, but it's unclear 9141 // that would be a benefit as it would not eliminate any operations, just 9142 // perform one more step in scalar code before moving to the vector unit. 9143 if (BuildVectorSDNode *BV = 9144 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) { 9145 // Bail out if the vector isn't a constant. 9146 if (!BV->isConstant()) 9147 return SDValue(); 9148 9149 // Everything checks out. Build up the new and improved node. 9150 SDLoc DL(N); 9151 EVT IntVT = BV->getValueType(0); 9152 // Create a new constant of the appropriate type for the transformed 9153 // DAG. 9154 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0)); 9155 // The AND node needs bitcasts to/from an integer vector type around it. 9156 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst); 9157 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT, 9158 N->getOperand(0)->getOperand(0), MaskConst); 9159 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd); 9160 return Res; 9161 } 9162 9163 return SDValue(); 9164 } 9165 9166 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG, 9167 const AArch64Subtarget *Subtarget) { 9168 // First try to optimize away the conversion when it's conditionally from 9169 // a constant. Vectors only. 9170 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG)) 9171 return Res; 9172 9173 EVT VT = N->getValueType(0); 9174 if (VT != MVT::f32 && VT != MVT::f64) 9175 return SDValue(); 9176 9177 // Only optimize when the source and destination types have the same width. 9178 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits()) 9179 return SDValue(); 9180 9181 // If the result of an integer load is only used by an integer-to-float 9182 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead. 9183 // This eliminates an "integer-to-vector-move" UOP and improves throughput. 9184 SDValue N0 = N->getOperand(0); 9185 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() && 9186 // Do not change the width of a volatile load. 9187 !cast<LoadSDNode>(N0)->isVolatile()) { 9188 LoadSDNode *LN0 = cast<LoadSDNode>(N0); 9189 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(), 9190 LN0->getPointerInfo(), LN0->getAlignment(), 9191 LN0->getMemOperand()->getFlags()); 9192 9193 // Make sure successors of the original load stay after it by updating them 9194 // to use the new Chain. 9195 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1)); 9196 9197 unsigned Opcode = 9198 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF; 9199 return DAG.getNode(Opcode, SDLoc(N), VT, Load); 9200 } 9201 9202 return SDValue(); 9203 } 9204 9205 /// Fold a floating-point multiply by power of two into floating-point to 9206 /// fixed-point conversion. 9207 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG, 9208 TargetLowering::DAGCombinerInfo &DCI, 9209 const AArch64Subtarget *Subtarget) { 9210 if (!Subtarget->hasNEON()) 9211 return SDValue(); 9212 9213 if (!N->getValueType(0).isSimple()) 9214 return SDValue(); 9215 9216 SDValue Op = N->getOperand(0); 9217 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 9218 Op.getOpcode() != ISD::FMUL) 9219 return SDValue(); 9220 9221 SDValue ConstVec = Op->getOperand(1); 9222 if (!isa<BuildVectorSDNode>(ConstVec)) 9223 return SDValue(); 9224 9225 MVT FloatTy = Op.getSimpleValueType().getVectorElementType(); 9226 uint32_t FloatBits = FloatTy.getSizeInBits(); 9227 if (FloatBits != 32 && FloatBits != 64) 9228 return SDValue(); 9229 9230 MVT IntTy = N->getSimpleValueType(0).getVectorElementType(); 9231 uint32_t IntBits = IntTy.getSizeInBits(); 9232 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 9233 return SDValue(); 9234 9235 // Avoid conversions where iN is larger than the float (e.g., float -> i64). 9236 if (IntBits > FloatBits) 9237 return SDValue(); 9238 9239 BitVector UndefElements; 9240 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 9241 int32_t Bits = IntBits == 64 ? 64 : 32; 9242 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1); 9243 if (C == -1 || C == 0 || C > Bits) 9244 return SDValue(); 9245 9246 MVT ResTy; 9247 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 9248 switch (NumLanes) { 9249 default: 9250 return SDValue(); 9251 case 2: 9252 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 9253 break; 9254 case 4: 9255 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; 9256 break; 9257 } 9258 9259 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) 9260 return SDValue(); 9261 9262 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) && 9263 "Illegal vector type after legalization"); 9264 9265 SDLoc DL(N); 9266 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 9267 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs 9268 : Intrinsic::aarch64_neon_vcvtfp2fxu; 9269 SDValue FixConv = 9270 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy, 9271 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), 9272 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32)); 9273 // We can handle smaller integers by generating an extra trunc. 9274 if (IntBits < FloatBits) 9275 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv); 9276 9277 return FixConv; 9278 } 9279 9280 /// Fold a floating-point divide by power of two into fixed-point to 9281 /// floating-point conversion. 9282 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG, 9283 TargetLowering::DAGCombinerInfo &DCI, 9284 const AArch64Subtarget *Subtarget) { 9285 if (!Subtarget->hasNEON()) 9286 return SDValue(); 9287 9288 SDValue Op = N->getOperand(0); 9289 unsigned Opc = Op->getOpcode(); 9290 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() || 9291 !Op.getOperand(0).getValueType().isSimple() || 9292 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP)) 9293 return SDValue(); 9294 9295 SDValue ConstVec = N->getOperand(1); 9296 if (!isa<BuildVectorSDNode>(ConstVec)) 9297 return SDValue(); 9298 9299 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType(); 9300 int32_t IntBits = IntTy.getSizeInBits(); 9301 if (IntBits != 16 && IntBits != 32 && IntBits != 64) 9302 return SDValue(); 9303 9304 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType(); 9305 int32_t FloatBits = FloatTy.getSizeInBits(); 9306 if (FloatBits != 32 && FloatBits != 64) 9307 return SDValue(); 9308 9309 // Avoid conversions where iN is larger than the float (e.g., i64 -> float). 9310 if (IntBits > FloatBits) 9311 return SDValue(); 9312 9313 BitVector UndefElements; 9314 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec); 9315 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1); 9316 if (C == -1 || C == 0 || C > FloatBits) 9317 return SDValue(); 9318 9319 MVT ResTy; 9320 unsigned NumLanes = Op.getValueType().getVectorNumElements(); 9321 switch (NumLanes) { 9322 default: 9323 return SDValue(); 9324 case 2: 9325 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64; 9326 break; 9327 case 4: 9328 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64; 9329 break; 9330 } 9331 9332 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps()) 9333 return SDValue(); 9334 9335 SDLoc DL(N); 9336 SDValue ConvInput = Op.getOperand(0); 9337 bool IsSigned = Opc == ISD::SINT_TO_FP; 9338 if (IntBits < FloatBits) 9339 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, 9340 ResTy, ConvInput); 9341 9342 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp 9343 : Intrinsic::aarch64_neon_vcvtfxu2fp; 9344 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(), 9345 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput, 9346 DAG.getConstant(C, DL, MVT::i32)); 9347 } 9348 9349 /// An EXTR instruction is made up of two shifts, ORed together. This helper 9350 /// searches for and classifies those shifts. 9351 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount, 9352 bool &FromHi) { 9353 if (N.getOpcode() == ISD::SHL) 9354 FromHi = false; 9355 else if (N.getOpcode() == ISD::SRL) 9356 FromHi = true; 9357 else 9358 return false; 9359 9360 if (!isa<ConstantSDNode>(N.getOperand(1))) 9361 return false; 9362 9363 ShiftAmount = N->getConstantOperandVal(1); 9364 Src = N->getOperand(0); 9365 return true; 9366 } 9367 9368 /// EXTR instruction extracts a contiguous chunk of bits from two existing 9369 /// registers viewed as a high/low pair. This function looks for the pattern: 9370 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it 9371 /// with an EXTR. Can't quite be done in TableGen because the two immediates 9372 /// aren't independent. 9373 static SDValue tryCombineToEXTR(SDNode *N, 9374 TargetLowering::DAGCombinerInfo &DCI) { 9375 SelectionDAG &DAG = DCI.DAG; 9376 SDLoc DL(N); 9377 EVT VT = N->getValueType(0); 9378 9379 assert(N->getOpcode() == ISD::OR && "Unexpected root"); 9380 9381 if (VT != MVT::i32 && VT != MVT::i64) 9382 return SDValue(); 9383 9384 SDValue LHS; 9385 uint32_t ShiftLHS = 0; 9386 bool LHSFromHi = false; 9387 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi)) 9388 return SDValue(); 9389 9390 SDValue RHS; 9391 uint32_t ShiftRHS = 0; 9392 bool RHSFromHi = false; 9393 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi)) 9394 return SDValue(); 9395 9396 // If they're both trying to come from the high part of the register, they're 9397 // not really an EXTR. 9398 if (LHSFromHi == RHSFromHi) 9399 return SDValue(); 9400 9401 if (ShiftLHS + ShiftRHS != VT.getSizeInBits()) 9402 return SDValue(); 9403 9404 if (LHSFromHi) { 9405 std::swap(LHS, RHS); 9406 std::swap(ShiftLHS, ShiftRHS); 9407 } 9408 9409 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS, 9410 DAG.getConstant(ShiftRHS, DL, MVT::i64)); 9411 } 9412 9413 static SDValue tryCombineToBSL(SDNode *N, 9414 TargetLowering::DAGCombinerInfo &DCI) { 9415 EVT VT = N->getValueType(0); 9416 SelectionDAG &DAG = DCI.DAG; 9417 SDLoc DL(N); 9418 9419 if (!VT.isVector()) 9420 return SDValue(); 9421 9422 SDValue N0 = N->getOperand(0); 9423 if (N0.getOpcode() != ISD::AND) 9424 return SDValue(); 9425 9426 SDValue N1 = N->getOperand(1); 9427 if (N1.getOpcode() != ISD::AND) 9428 return SDValue(); 9429 9430 // We only have to look for constant vectors here since the general, variable 9431 // case can be handled in TableGen. 9432 unsigned Bits = VT.getScalarSizeInBits(); 9433 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1); 9434 for (int i = 1; i >= 0; --i) 9435 for (int j = 1; j >= 0; --j) { 9436 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i)); 9437 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j)); 9438 if (!BVN0 || !BVN1) 9439 continue; 9440 9441 bool FoundMatch = true; 9442 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) { 9443 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k)); 9444 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k)); 9445 if (!CN0 || !CN1 || 9446 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) { 9447 FoundMatch = false; 9448 break; 9449 } 9450 } 9451 9452 if (FoundMatch) 9453 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0), 9454 N0->getOperand(1 - i), N1->getOperand(1 - j)); 9455 } 9456 9457 return SDValue(); 9458 } 9459 9460 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 9461 const AArch64Subtarget *Subtarget) { 9462 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) 9463 SelectionDAG &DAG = DCI.DAG; 9464 EVT VT = N->getValueType(0); 9465 9466 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9467 return SDValue(); 9468 9469 if (SDValue Res = tryCombineToEXTR(N, DCI)) 9470 return Res; 9471 9472 if (SDValue Res = tryCombineToBSL(N, DCI)) 9473 return Res; 9474 9475 return SDValue(); 9476 } 9477 9478 static SDValue performANDCombine(SDNode *N, 9479 TargetLowering::DAGCombinerInfo &DCI) { 9480 SelectionDAG &DAG = DCI.DAG; 9481 SDValue LHS = N->getOperand(0); 9482 EVT VT = N->getValueType(0); 9483 if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT)) 9484 return SDValue(); 9485 9486 BuildVectorSDNode *BVN = 9487 dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode()); 9488 if (!BVN) 9489 return SDValue(); 9490 9491 // AND does not accept an immediate, so check if we can use a BIC immediate 9492 // instruction instead. We do this here instead of using a (and x, (mvni imm)) 9493 // pattern in isel, because some immediates may be lowered to the preferred 9494 // (and x, (movi imm)) form, even though an mvni representation also exists. 9495 APInt DefBits(VT.getSizeInBits(), 0); 9496 APInt UndefBits(VT.getSizeInBits(), 0); 9497 if (resolveBuildVector(BVN, DefBits, UndefBits)) { 9498 SDValue NewOp; 9499 9500 DefBits = ~DefBits; 9501 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG, 9502 DefBits, &LHS)) || 9503 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG, 9504 DefBits, &LHS))) 9505 return NewOp; 9506 9507 UndefBits = ~UndefBits; 9508 if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG, 9509 UndefBits, &LHS)) || 9510 (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG, 9511 UndefBits, &LHS))) 9512 return NewOp; 9513 } 9514 9515 return SDValue(); 9516 } 9517 9518 static SDValue performSRLCombine(SDNode *N, 9519 TargetLowering::DAGCombinerInfo &DCI) { 9520 SelectionDAG &DAG = DCI.DAG; 9521 EVT VT = N->getValueType(0); 9522 if (VT != MVT::i32 && VT != MVT::i64) 9523 return SDValue(); 9524 9525 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the 9526 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32) 9527 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero. 9528 SDValue N0 = N->getOperand(0); 9529 if (N0.getOpcode() == ISD::BSWAP) { 9530 SDLoc DL(N); 9531 SDValue N1 = N->getOperand(1); 9532 SDValue N00 = N0.getOperand(0); 9533 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) { 9534 uint64_t ShiftAmt = C->getZExtValue(); 9535 if (VT == MVT::i32 && ShiftAmt == 16 && 9536 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16))) 9537 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 9538 if (VT == MVT::i64 && ShiftAmt == 32 && 9539 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32))) 9540 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1); 9541 } 9542 } 9543 return SDValue(); 9544 } 9545 9546 static SDValue performBitcastCombine(SDNode *N, 9547 TargetLowering::DAGCombinerInfo &DCI, 9548 SelectionDAG &DAG) { 9549 // Wait 'til after everything is legalized to try this. That way we have 9550 // legal vector types and such. 9551 if (DCI.isBeforeLegalizeOps()) 9552 return SDValue(); 9553 9554 // Remove extraneous bitcasts around an extract_subvector. 9555 // For example, 9556 // (v4i16 (bitconvert 9557 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1))))) 9558 // becomes 9559 // (extract_subvector ((v8i16 ...), (i64 4))) 9560 9561 // Only interested in 64-bit vectors as the ultimate result. 9562 EVT VT = N->getValueType(0); 9563 if (!VT.isVector()) 9564 return SDValue(); 9565 if (VT.getSimpleVT().getSizeInBits() != 64) 9566 return SDValue(); 9567 // Is the operand an extract_subvector starting at the beginning or halfway 9568 // point of the vector? A low half may also come through as an 9569 // EXTRACT_SUBREG, so look for that, too. 9570 SDValue Op0 = N->getOperand(0); 9571 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR && 9572 !(Op0->isMachineOpcode() && 9573 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG)) 9574 return SDValue(); 9575 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue(); 9576 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) { 9577 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0) 9578 return SDValue(); 9579 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) { 9580 if (idx != AArch64::dsub) 9581 return SDValue(); 9582 // The dsub reference is equivalent to a lane zero subvector reference. 9583 idx = 0; 9584 } 9585 // Look through the bitcast of the input to the extract. 9586 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST) 9587 return SDValue(); 9588 SDValue Source = Op0->getOperand(0)->getOperand(0); 9589 // If the source type has twice the number of elements as our destination 9590 // type, we know this is an extract of the high or low half of the vector. 9591 EVT SVT = Source->getValueType(0); 9592 if (!SVT.isVector() || 9593 SVT.getVectorNumElements() != VT.getVectorNumElements() * 2) 9594 return SDValue(); 9595 9596 LLVM_DEBUG( 9597 dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n"); 9598 9599 // Create the simplified form to just extract the low or high half of the 9600 // vector directly rather than bothering with the bitcasts. 9601 SDLoc dl(N); 9602 unsigned NumElements = VT.getVectorNumElements(); 9603 if (idx) { 9604 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64); 9605 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx); 9606 } else { 9607 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32); 9608 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT, 9609 Source, SubReg), 9610 0); 9611 } 9612 } 9613 9614 static SDValue performConcatVectorsCombine(SDNode *N, 9615 TargetLowering::DAGCombinerInfo &DCI, 9616 SelectionDAG &DAG) { 9617 SDLoc dl(N); 9618 EVT VT = N->getValueType(0); 9619 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1); 9620 9621 // Optimize concat_vectors of truncated vectors, where the intermediate 9622 // type is illegal, to avoid said illegality, e.g., 9623 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))), 9624 // (v2i16 (truncate (v2i64))))) 9625 // -> 9626 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))), 9627 // (v4i32 (bitcast (v2i64))), 9628 // <0, 2, 4, 6>))) 9629 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed 9630 // on both input and result type, so we might generate worse code. 9631 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8. 9632 if (N->getNumOperands() == 2 && 9633 N0->getOpcode() == ISD::TRUNCATE && 9634 N1->getOpcode() == ISD::TRUNCATE) { 9635 SDValue N00 = N0->getOperand(0); 9636 SDValue N10 = N1->getOperand(0); 9637 EVT N00VT = N00.getValueType(); 9638 9639 if (N00VT == N10.getValueType() && 9640 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) && 9641 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) { 9642 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16); 9643 SmallVector<int, 8> Mask(MidVT.getVectorNumElements()); 9644 for (size_t i = 0; i < Mask.size(); ++i) 9645 Mask[i] = i * 2; 9646 return DAG.getNode(ISD::TRUNCATE, dl, VT, 9647 DAG.getVectorShuffle( 9648 MidVT, dl, 9649 DAG.getNode(ISD::BITCAST, dl, MidVT, N00), 9650 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask)); 9651 } 9652 } 9653 9654 // Wait 'til after everything is legalized to try this. That way we have 9655 // legal vector types and such. 9656 if (DCI.isBeforeLegalizeOps()) 9657 return SDValue(); 9658 9659 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector 9660 // splat. The indexed instructions are going to be expecting a DUPLANE64, so 9661 // canonicalise to that. 9662 if (N0 == N1 && VT.getVectorNumElements() == 2) { 9663 assert(VT.getScalarSizeInBits() == 64); 9664 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG), 9665 DAG.getConstant(0, dl, MVT::i64)); 9666 } 9667 9668 // Canonicalise concat_vectors so that the right-hand vector has as few 9669 // bit-casts as possible before its real operation. The primary matching 9670 // destination for these operations will be the narrowing "2" instructions, 9671 // which depend on the operation being performed on this right-hand vector. 9672 // For example, 9673 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS)))) 9674 // becomes 9675 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS)) 9676 9677 if (N1->getOpcode() != ISD::BITCAST) 9678 return SDValue(); 9679 SDValue RHS = N1->getOperand(0); 9680 MVT RHSTy = RHS.getValueType().getSimpleVT(); 9681 // If the RHS is not a vector, this is not the pattern we're looking for. 9682 if (!RHSTy.isVector()) 9683 return SDValue(); 9684 9685 LLVM_DEBUG( 9686 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n"); 9687 9688 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(), 9689 RHSTy.getVectorNumElements() * 2); 9690 return DAG.getNode(ISD::BITCAST, dl, VT, 9691 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy, 9692 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0), 9693 RHS)); 9694 } 9695 9696 static SDValue tryCombineFixedPointConvert(SDNode *N, 9697 TargetLowering::DAGCombinerInfo &DCI, 9698 SelectionDAG &DAG) { 9699 // Wait until after everything is legalized to try this. That way we have 9700 // legal vector types and such. 9701 if (DCI.isBeforeLegalizeOps()) 9702 return SDValue(); 9703 // Transform a scalar conversion of a value from a lane extract into a 9704 // lane extract of a vector conversion. E.g., from foo1 to foo2: 9705 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); } 9706 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; } 9707 // 9708 // The second form interacts better with instruction selection and the 9709 // register allocator to avoid cross-class register copies that aren't 9710 // coalescable due to a lane reference. 9711 9712 // Check the operand and see if it originates from a lane extract. 9713 SDValue Op1 = N->getOperand(1); 9714 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) { 9715 // Yep, no additional predication needed. Perform the transform. 9716 SDValue IID = N->getOperand(0); 9717 SDValue Shift = N->getOperand(2); 9718 SDValue Vec = Op1.getOperand(0); 9719 SDValue Lane = Op1.getOperand(1); 9720 EVT ResTy = N->getValueType(0); 9721 EVT VecResTy; 9722 SDLoc DL(N); 9723 9724 // The vector width should be 128 bits by the time we get here, even 9725 // if it started as 64 bits (the extract_vector handling will have 9726 // done so). 9727 assert(Vec.getValueSizeInBits() == 128 && 9728 "unexpected vector size on extract_vector_elt!"); 9729 if (Vec.getValueType() == MVT::v4i32) 9730 VecResTy = MVT::v4f32; 9731 else if (Vec.getValueType() == MVT::v2i64) 9732 VecResTy = MVT::v2f64; 9733 else 9734 llvm_unreachable("unexpected vector type!"); 9735 9736 SDValue Convert = 9737 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift); 9738 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane); 9739 } 9740 return SDValue(); 9741 } 9742 9743 // AArch64 high-vector "long" operations are formed by performing the non-high 9744 // version on an extract_subvector of each operand which gets the high half: 9745 // 9746 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS)) 9747 // 9748 // However, there are cases which don't have an extract_high explicitly, but 9749 // have another operation that can be made compatible with one for free. For 9750 // example: 9751 // 9752 // (dupv64 scalar) --> (extract_high (dup128 scalar)) 9753 // 9754 // This routine does the actual conversion of such DUPs, once outer routines 9755 // have determined that everything else is in order. 9756 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold 9757 // similarly here. 9758 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) { 9759 switch (N.getOpcode()) { 9760 case AArch64ISD::DUP: 9761 case AArch64ISD::DUPLANE8: 9762 case AArch64ISD::DUPLANE16: 9763 case AArch64ISD::DUPLANE32: 9764 case AArch64ISD::DUPLANE64: 9765 case AArch64ISD::MOVI: 9766 case AArch64ISD::MOVIshift: 9767 case AArch64ISD::MOVIedit: 9768 case AArch64ISD::MOVImsl: 9769 case AArch64ISD::MVNIshift: 9770 case AArch64ISD::MVNImsl: 9771 break; 9772 default: 9773 // FMOV could be supported, but isn't very useful, as it would only occur 9774 // if you passed a bitcast' floating point immediate to an eligible long 9775 // integer op (addl, smull, ...). 9776 return SDValue(); 9777 } 9778 9779 MVT NarrowTy = N.getSimpleValueType(); 9780 if (!NarrowTy.is64BitVector()) 9781 return SDValue(); 9782 9783 MVT ElementTy = NarrowTy.getVectorElementType(); 9784 unsigned NumElems = NarrowTy.getVectorNumElements(); 9785 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2); 9786 9787 SDLoc dl(N); 9788 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy, 9789 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()), 9790 DAG.getConstant(NumElems, dl, MVT::i64)); 9791 } 9792 9793 static bool isEssentiallyExtractHighSubvector(SDValue N) { 9794 if (N.getOpcode() == ISD::BITCAST) 9795 N = N.getOperand(0); 9796 if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR) 9797 return false; 9798 return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() == 9799 N.getOperand(0).getValueType().getVectorNumElements() / 2; 9800 } 9801 9802 /// Helper structure to keep track of ISD::SET_CC operands. 9803 struct GenericSetCCInfo { 9804 const SDValue *Opnd0; 9805 const SDValue *Opnd1; 9806 ISD::CondCode CC; 9807 }; 9808 9809 /// Helper structure to keep track of a SET_CC lowered into AArch64 code. 9810 struct AArch64SetCCInfo { 9811 const SDValue *Cmp; 9812 AArch64CC::CondCode CC; 9813 }; 9814 9815 /// Helper structure to keep track of SetCC information. 9816 union SetCCInfo { 9817 GenericSetCCInfo Generic; 9818 AArch64SetCCInfo AArch64; 9819 }; 9820 9821 /// Helper structure to be able to read SetCC information. If set to 9822 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a 9823 /// GenericSetCCInfo. 9824 struct SetCCInfoAndKind { 9825 SetCCInfo Info; 9826 bool IsAArch64; 9827 }; 9828 9829 /// Check whether or not \p Op is a SET_CC operation, either a generic or 9830 /// an 9831 /// AArch64 lowered one. 9832 /// \p SetCCInfo is filled accordingly. 9833 /// \post SetCCInfo is meanginfull only when this function returns true. 9834 /// \return True when Op is a kind of SET_CC operation. 9835 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) { 9836 // If this is a setcc, this is straight forward. 9837 if (Op.getOpcode() == ISD::SETCC) { 9838 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0); 9839 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1); 9840 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 9841 SetCCInfo.IsAArch64 = false; 9842 return true; 9843 } 9844 // Otherwise, check if this is a matching csel instruction. 9845 // In other words: 9846 // - csel 1, 0, cc 9847 // - csel 0, 1, !cc 9848 if (Op.getOpcode() != AArch64ISD::CSEL) 9849 return false; 9850 // Set the information about the operands. 9851 // TODO: we want the operands of the Cmp not the csel 9852 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3); 9853 SetCCInfo.IsAArch64 = true; 9854 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>( 9855 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue()); 9856 9857 // Check that the operands matches the constraints: 9858 // (1) Both operands must be constants. 9859 // (2) One must be 1 and the other must be 0. 9860 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0)); 9861 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 9862 9863 // Check (1). 9864 if (!TValue || !FValue) 9865 return false; 9866 9867 // Check (2). 9868 if (!TValue->isOne()) { 9869 // Update the comparison when we are interested in !cc. 9870 std::swap(TValue, FValue); 9871 SetCCInfo.Info.AArch64.CC = 9872 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC); 9873 } 9874 return TValue->isOne() && FValue->isNullValue(); 9875 } 9876 9877 // Returns true if Op is setcc or zext of setcc. 9878 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) { 9879 if (isSetCC(Op, Info)) 9880 return true; 9881 return ((Op.getOpcode() == ISD::ZERO_EXTEND) && 9882 isSetCC(Op->getOperand(0), Info)); 9883 } 9884 9885 // The folding we want to perform is: 9886 // (add x, [zext] (setcc cc ...) ) 9887 // --> 9888 // (csel x, (add x, 1), !cc ...) 9889 // 9890 // The latter will get matched to a CSINC instruction. 9891 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) { 9892 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!"); 9893 SDValue LHS = Op->getOperand(0); 9894 SDValue RHS = Op->getOperand(1); 9895 SetCCInfoAndKind InfoAndKind; 9896 9897 // If neither operand is a SET_CC, give up. 9898 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) { 9899 std::swap(LHS, RHS); 9900 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) 9901 return SDValue(); 9902 } 9903 9904 // FIXME: This could be generatized to work for FP comparisons. 9905 EVT CmpVT = InfoAndKind.IsAArch64 9906 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType() 9907 : InfoAndKind.Info.Generic.Opnd0->getValueType(); 9908 if (CmpVT != MVT::i32 && CmpVT != MVT::i64) 9909 return SDValue(); 9910 9911 SDValue CCVal; 9912 SDValue Cmp; 9913 SDLoc dl(Op); 9914 if (InfoAndKind.IsAArch64) { 9915 CCVal = DAG.getConstant( 9916 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl, 9917 MVT::i32); 9918 Cmp = *InfoAndKind.Info.AArch64.Cmp; 9919 } else 9920 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0, 9921 *InfoAndKind.Info.Generic.Opnd1, 9922 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true), 9923 CCVal, DAG, dl); 9924 9925 EVT VT = Op->getValueType(0); 9926 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT)); 9927 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp); 9928 } 9929 9930 // The basic add/sub long vector instructions have variants with "2" on the end 9931 // which act on the high-half of their inputs. They are normally matched by 9932 // patterns like: 9933 // 9934 // (add (zeroext (extract_high LHS)), 9935 // (zeroext (extract_high RHS))) 9936 // -> uaddl2 vD, vN, vM 9937 // 9938 // However, if one of the extracts is something like a duplicate, this 9939 // instruction can still be used profitably. This function puts the DAG into a 9940 // more appropriate form for those patterns to trigger. 9941 static SDValue performAddSubLongCombine(SDNode *N, 9942 TargetLowering::DAGCombinerInfo &DCI, 9943 SelectionDAG &DAG) { 9944 if (DCI.isBeforeLegalizeOps()) 9945 return SDValue(); 9946 9947 MVT VT = N->getSimpleValueType(0); 9948 if (!VT.is128BitVector()) { 9949 if (N->getOpcode() == ISD::ADD) 9950 return performSetccAddFolding(N, DAG); 9951 return SDValue(); 9952 } 9953 9954 // Make sure both branches are extended in the same way. 9955 SDValue LHS = N->getOperand(0); 9956 SDValue RHS = N->getOperand(1); 9957 if ((LHS.getOpcode() != ISD::ZERO_EXTEND && 9958 LHS.getOpcode() != ISD::SIGN_EXTEND) || 9959 LHS.getOpcode() != RHS.getOpcode()) 9960 return SDValue(); 9961 9962 unsigned ExtType = LHS.getOpcode(); 9963 9964 // It's not worth doing if at least one of the inputs isn't already an 9965 // extract, but we don't know which it'll be so we have to try both. 9966 if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) { 9967 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG); 9968 if (!RHS.getNode()) 9969 return SDValue(); 9970 9971 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS); 9972 } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) { 9973 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG); 9974 if (!LHS.getNode()) 9975 return SDValue(); 9976 9977 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS); 9978 } 9979 9980 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS); 9981 } 9982 9983 // Massage DAGs which we can use the high-half "long" operations on into 9984 // something isel will recognize better. E.g. 9985 // 9986 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) --> 9987 // (aarch64_neon_umull (extract_high (v2i64 vec))) 9988 // (extract_high (v2i64 (dup128 scalar))))) 9989 // 9990 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N, 9991 TargetLowering::DAGCombinerInfo &DCI, 9992 SelectionDAG &DAG) { 9993 if (DCI.isBeforeLegalizeOps()) 9994 return SDValue(); 9995 9996 SDValue LHS = N->getOperand(1); 9997 SDValue RHS = N->getOperand(2); 9998 assert(LHS.getValueType().is64BitVector() && 9999 RHS.getValueType().is64BitVector() && 10000 "unexpected shape for long operation"); 10001 10002 // Either node could be a DUP, but it's not worth doing both of them (you'd 10003 // just as well use the non-high version) so look for a corresponding extract 10004 // operation on the other "wing". 10005 if (isEssentiallyExtractHighSubvector(LHS)) { 10006 RHS = tryExtendDUPToExtractHigh(RHS, DAG); 10007 if (!RHS.getNode()) 10008 return SDValue(); 10009 } else if (isEssentiallyExtractHighSubvector(RHS)) { 10010 LHS = tryExtendDUPToExtractHigh(LHS, DAG); 10011 if (!LHS.getNode()) 10012 return SDValue(); 10013 } 10014 10015 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0), 10016 N->getOperand(0), LHS, RHS); 10017 } 10018 10019 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) { 10020 MVT ElemTy = N->getSimpleValueType(0).getScalarType(); 10021 unsigned ElemBits = ElemTy.getSizeInBits(); 10022 10023 int64_t ShiftAmount; 10024 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) { 10025 APInt SplatValue, SplatUndef; 10026 unsigned SplatBitSize; 10027 bool HasAnyUndefs; 10028 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize, 10029 HasAnyUndefs, ElemBits) || 10030 SplatBitSize != ElemBits) 10031 return SDValue(); 10032 10033 ShiftAmount = SplatValue.getSExtValue(); 10034 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) { 10035 ShiftAmount = CVN->getSExtValue(); 10036 } else 10037 return SDValue(); 10038 10039 unsigned Opcode; 10040 bool IsRightShift; 10041 switch (IID) { 10042 default: 10043 llvm_unreachable("Unknown shift intrinsic"); 10044 case Intrinsic::aarch64_neon_sqshl: 10045 Opcode = AArch64ISD::SQSHL_I; 10046 IsRightShift = false; 10047 break; 10048 case Intrinsic::aarch64_neon_uqshl: 10049 Opcode = AArch64ISD::UQSHL_I; 10050 IsRightShift = false; 10051 break; 10052 case Intrinsic::aarch64_neon_srshl: 10053 Opcode = AArch64ISD::SRSHR_I; 10054 IsRightShift = true; 10055 break; 10056 case Intrinsic::aarch64_neon_urshl: 10057 Opcode = AArch64ISD::URSHR_I; 10058 IsRightShift = true; 10059 break; 10060 case Intrinsic::aarch64_neon_sqshlu: 10061 Opcode = AArch64ISD::SQSHLU_I; 10062 IsRightShift = false; 10063 break; 10064 } 10065 10066 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) { 10067 SDLoc dl(N); 10068 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 10069 DAG.getConstant(-ShiftAmount, dl, MVT::i32)); 10070 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) { 10071 SDLoc dl(N); 10072 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1), 10073 DAG.getConstant(ShiftAmount, dl, MVT::i32)); 10074 } 10075 10076 return SDValue(); 10077 } 10078 10079 // The CRC32[BH] instructions ignore the high bits of their data operand. Since 10080 // the intrinsics must be legal and take an i32, this means there's almost 10081 // certainly going to be a zext in the DAG which we can eliminate. 10082 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) { 10083 SDValue AndN = N->getOperand(2); 10084 if (AndN.getOpcode() != ISD::AND) 10085 return SDValue(); 10086 10087 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1)); 10088 if (!CMask || CMask->getZExtValue() != Mask) 10089 return SDValue(); 10090 10091 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32, 10092 N->getOperand(0), N->getOperand(1), AndN.getOperand(0)); 10093 } 10094 10095 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N, 10096 SelectionDAG &DAG) { 10097 SDLoc dl(N); 10098 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), 10099 DAG.getNode(Opc, dl, 10100 N->getOperand(1).getSimpleValueType(), 10101 N->getOperand(1)), 10102 DAG.getConstant(0, dl, MVT::i64)); 10103 } 10104 10105 static SDValue performIntrinsicCombine(SDNode *N, 10106 TargetLowering::DAGCombinerInfo &DCI, 10107 const AArch64Subtarget *Subtarget) { 10108 SelectionDAG &DAG = DCI.DAG; 10109 unsigned IID = getIntrinsicID(N); 10110 switch (IID) { 10111 default: 10112 break; 10113 case Intrinsic::aarch64_neon_vcvtfxs2fp: 10114 case Intrinsic::aarch64_neon_vcvtfxu2fp: 10115 return tryCombineFixedPointConvert(N, DCI, DAG); 10116 case Intrinsic::aarch64_neon_saddv: 10117 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG); 10118 case Intrinsic::aarch64_neon_uaddv: 10119 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG); 10120 case Intrinsic::aarch64_neon_sminv: 10121 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG); 10122 case Intrinsic::aarch64_neon_uminv: 10123 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG); 10124 case Intrinsic::aarch64_neon_smaxv: 10125 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG); 10126 case Intrinsic::aarch64_neon_umaxv: 10127 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG); 10128 case Intrinsic::aarch64_neon_fmax: 10129 return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0), 10130 N->getOperand(1), N->getOperand(2)); 10131 case Intrinsic::aarch64_neon_fmin: 10132 return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0), 10133 N->getOperand(1), N->getOperand(2)); 10134 case Intrinsic::aarch64_neon_fmaxnm: 10135 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0), 10136 N->getOperand(1), N->getOperand(2)); 10137 case Intrinsic::aarch64_neon_fminnm: 10138 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0), 10139 N->getOperand(1), N->getOperand(2)); 10140 case Intrinsic::aarch64_neon_smull: 10141 case Intrinsic::aarch64_neon_umull: 10142 case Intrinsic::aarch64_neon_pmull: 10143 case Intrinsic::aarch64_neon_sqdmull: 10144 return tryCombineLongOpWithDup(IID, N, DCI, DAG); 10145 case Intrinsic::aarch64_neon_sqshl: 10146 case Intrinsic::aarch64_neon_uqshl: 10147 case Intrinsic::aarch64_neon_sqshlu: 10148 case Intrinsic::aarch64_neon_srshl: 10149 case Intrinsic::aarch64_neon_urshl: 10150 return tryCombineShiftImm(IID, N, DAG); 10151 case Intrinsic::aarch64_crc32b: 10152 case Intrinsic::aarch64_crc32cb: 10153 return tryCombineCRC32(0xff, N, DAG); 10154 case Intrinsic::aarch64_crc32h: 10155 case Intrinsic::aarch64_crc32ch: 10156 return tryCombineCRC32(0xffff, N, DAG); 10157 } 10158 return SDValue(); 10159 } 10160 10161 static SDValue performExtendCombine(SDNode *N, 10162 TargetLowering::DAGCombinerInfo &DCI, 10163 SelectionDAG &DAG) { 10164 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then 10165 // we can convert that DUP into another extract_high (of a bigger DUP), which 10166 // helps the backend to decide that an sabdl2 would be useful, saving a real 10167 // extract_high operation. 10168 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND && 10169 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) { 10170 SDNode *ABDNode = N->getOperand(0).getNode(); 10171 unsigned IID = getIntrinsicID(ABDNode); 10172 if (IID == Intrinsic::aarch64_neon_sabd || 10173 IID == Intrinsic::aarch64_neon_uabd) { 10174 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG); 10175 if (!NewABD.getNode()) 10176 return SDValue(); 10177 10178 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), 10179 NewABD); 10180 } 10181 } 10182 10183 // This is effectively a custom type legalization for AArch64. 10184 // 10185 // Type legalization will split an extend of a small, legal, type to a larger 10186 // illegal type by first splitting the destination type, often creating 10187 // illegal source types, which then get legalized in isel-confusing ways, 10188 // leading to really terrible codegen. E.g., 10189 // %result = v8i32 sext v8i8 %value 10190 // becomes 10191 // %losrc = extract_subreg %value, ... 10192 // %hisrc = extract_subreg %value, ... 10193 // %lo = v4i32 sext v4i8 %losrc 10194 // %hi = v4i32 sext v4i8 %hisrc 10195 // Things go rapidly downhill from there. 10196 // 10197 // For AArch64, the [sz]ext vector instructions can only go up one element 10198 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32 10199 // take two instructions. 10200 // 10201 // This implies that the most efficient way to do the extend from v8i8 10202 // to two v4i32 values is to first extend the v8i8 to v8i16, then do 10203 // the normal splitting to happen for the v8i16->v8i32. 10204 10205 // This is pre-legalization to catch some cases where the default 10206 // type legalization will create ill-tempered code. 10207 if (!DCI.isBeforeLegalizeOps()) 10208 return SDValue(); 10209 10210 // We're only interested in cleaning things up for non-legal vector types 10211 // here. If both the source and destination are legal, things will just 10212 // work naturally without any fiddling. 10213 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10214 EVT ResVT = N->getValueType(0); 10215 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT)) 10216 return SDValue(); 10217 // If the vector type isn't a simple VT, it's beyond the scope of what 10218 // we're worried about here. Let legalization do its thing and hope for 10219 // the best. 10220 SDValue Src = N->getOperand(0); 10221 EVT SrcVT = Src->getValueType(0); 10222 if (!ResVT.isSimple() || !SrcVT.isSimple()) 10223 return SDValue(); 10224 10225 // If the source VT is a 64-bit vector, we can play games and get the 10226 // better results we want. 10227 if (SrcVT.getSizeInBits() != 64) 10228 return SDValue(); 10229 10230 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 10231 unsigned ElementCount = SrcVT.getVectorNumElements(); 10232 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount); 10233 SDLoc DL(N); 10234 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src); 10235 10236 // Now split the rest of the operation into two halves, each with a 64 10237 // bit source. 10238 EVT LoVT, HiVT; 10239 SDValue Lo, Hi; 10240 unsigned NumElements = ResVT.getVectorNumElements(); 10241 assert(!(NumElements & 1) && "Splitting vector, but not in half!"); 10242 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(), 10243 ResVT.getVectorElementType(), NumElements / 2); 10244 10245 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(), 10246 LoVT.getVectorNumElements()); 10247 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 10248 DAG.getConstant(0, DL, MVT::i64)); 10249 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src, 10250 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64)); 10251 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo); 10252 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi); 10253 10254 // Now combine the parts back together so we still have a single result 10255 // like the combiner expects. 10256 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi); 10257 } 10258 10259 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St, 10260 SDValue SplatVal, unsigned NumVecElts) { 10261 assert(!St.isTruncatingStore() && "cannot split truncating vector store"); 10262 unsigned OrigAlignment = St.getAlignment(); 10263 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8; 10264 10265 // Create scalar stores. This is at least as good as the code sequence for a 10266 // split unaligned store which is a dup.s, ext.b, and two stores. 10267 // Most of the time the three stores should be replaced by store pair 10268 // instructions (stp). 10269 SDLoc DL(&St); 10270 SDValue BasePtr = St.getBasePtr(); 10271 uint64_t BaseOffset = 0; 10272 10273 const MachinePointerInfo &PtrInfo = St.getPointerInfo(); 10274 SDValue NewST1 = 10275 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo, 10276 OrigAlignment, St.getMemOperand()->getFlags()); 10277 10278 // As this in ISel, we will not merge this add which may degrade results. 10279 if (BasePtr->getOpcode() == ISD::ADD && 10280 isa<ConstantSDNode>(BasePtr->getOperand(1))) { 10281 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue(); 10282 BasePtr = BasePtr->getOperand(0); 10283 } 10284 10285 unsigned Offset = EltOffset; 10286 while (--NumVecElts) { 10287 unsigned Alignment = MinAlign(OrigAlignment, Offset); 10288 SDValue OffsetPtr = 10289 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 10290 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64)); 10291 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr, 10292 PtrInfo.getWithOffset(Offset), Alignment, 10293 St.getMemOperand()->getFlags()); 10294 Offset += EltOffset; 10295 } 10296 return NewST1; 10297 } 10298 10299 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The 10300 /// load store optimizer pass will merge them to store pair stores. This should 10301 /// be better than a movi to create the vector zero followed by a vector store 10302 /// if the zero constant is not re-used, since one instructions and one register 10303 /// live range will be removed. 10304 /// 10305 /// For example, the final generated code should be: 10306 /// 10307 /// stp xzr, xzr, [x0] 10308 /// 10309 /// instead of: 10310 /// 10311 /// movi v0.2d, #0 10312 /// str q0, [x0] 10313 /// 10314 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) { 10315 SDValue StVal = St.getValue(); 10316 EVT VT = StVal.getValueType(); 10317 10318 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or 10319 // 2, 3 or 4 i32 elements. 10320 int NumVecElts = VT.getVectorNumElements(); 10321 if (!(((NumVecElts == 2 || NumVecElts == 3) && 10322 VT.getVectorElementType().getSizeInBits() == 64) || 10323 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) && 10324 VT.getVectorElementType().getSizeInBits() == 32))) 10325 return SDValue(); 10326 10327 if (StVal.getOpcode() != ISD::BUILD_VECTOR) 10328 return SDValue(); 10329 10330 // If the zero constant has more than one use then the vector store could be 10331 // better since the constant mov will be amortized and stp q instructions 10332 // should be able to be formed. 10333 if (!StVal.hasOneUse()) 10334 return SDValue(); 10335 10336 // If the store is truncating then it's going down to i16 or smaller, which 10337 // means it can be implemented in a single store anyway. 10338 if (St.isTruncatingStore()) 10339 return SDValue(); 10340 10341 // If the immediate offset of the address operand is too large for the stp 10342 // instruction, then bail out. 10343 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) { 10344 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1); 10345 if (Offset < -512 || Offset > 504) 10346 return SDValue(); 10347 } 10348 10349 for (int I = 0; I < NumVecElts; ++I) { 10350 SDValue EltVal = StVal.getOperand(I); 10351 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal)) 10352 return SDValue(); 10353 } 10354 10355 // Use a CopyFromReg WZR/XZR here to prevent 10356 // DAGCombiner::MergeConsecutiveStores from undoing this transformation. 10357 SDLoc DL(&St); 10358 unsigned ZeroReg; 10359 EVT ZeroVT; 10360 if (VT.getVectorElementType().getSizeInBits() == 32) { 10361 ZeroReg = AArch64::WZR; 10362 ZeroVT = MVT::i32; 10363 } else { 10364 ZeroReg = AArch64::XZR; 10365 ZeroVT = MVT::i64; 10366 } 10367 SDValue SplatVal = 10368 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT); 10369 return splitStoreSplat(DAG, St, SplatVal, NumVecElts); 10370 } 10371 10372 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar 10373 /// value. The load store optimizer pass will merge them to store pair stores. 10374 /// This has better performance than a splat of the scalar followed by a split 10375 /// vector store. Even if the stores are not merged it is four stores vs a dup, 10376 /// followed by an ext.b and two stores. 10377 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) { 10378 SDValue StVal = St.getValue(); 10379 EVT VT = StVal.getValueType(); 10380 10381 // Don't replace floating point stores, they possibly won't be transformed to 10382 // stp because of the store pair suppress pass. 10383 if (VT.isFloatingPoint()) 10384 return SDValue(); 10385 10386 // We can express a splat as store pair(s) for 2 or 4 elements. 10387 unsigned NumVecElts = VT.getVectorNumElements(); 10388 if (NumVecElts != 4 && NumVecElts != 2) 10389 return SDValue(); 10390 10391 // If the store is truncating then it's going down to i16 or smaller, which 10392 // means it can be implemented in a single store anyway. 10393 if (St.isTruncatingStore()) 10394 return SDValue(); 10395 10396 // Check that this is a splat. 10397 // Make sure that each of the relevant vector element locations are inserted 10398 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32. 10399 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1); 10400 SDValue SplatVal; 10401 for (unsigned I = 0; I < NumVecElts; ++I) { 10402 // Check for insert vector elements. 10403 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT) 10404 return SDValue(); 10405 10406 // Check that same value is inserted at each vector element. 10407 if (I == 0) 10408 SplatVal = StVal.getOperand(1); 10409 else if (StVal.getOperand(1) != SplatVal) 10410 return SDValue(); 10411 10412 // Check insert element index. 10413 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2)); 10414 if (!CIndex) 10415 return SDValue(); 10416 uint64_t IndexVal = CIndex->getZExtValue(); 10417 if (IndexVal >= NumVecElts) 10418 return SDValue(); 10419 IndexNotInserted.reset(IndexVal); 10420 10421 StVal = StVal.getOperand(0); 10422 } 10423 // Check that all vector element locations were inserted to. 10424 if (IndexNotInserted.any()) 10425 return SDValue(); 10426 10427 return splitStoreSplat(DAG, St, SplatVal, NumVecElts); 10428 } 10429 10430 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI, 10431 SelectionDAG &DAG, 10432 const AArch64Subtarget *Subtarget) { 10433 10434 StoreSDNode *S = cast<StoreSDNode>(N); 10435 if (S->isVolatile() || S->isIndexed()) 10436 return SDValue(); 10437 10438 SDValue StVal = S->getValue(); 10439 EVT VT = StVal.getValueType(); 10440 if (!VT.isVector()) 10441 return SDValue(); 10442 10443 // If we get a splat of zeros, convert this vector store to a store of 10444 // scalars. They will be merged into store pairs of xzr thereby removing one 10445 // instruction and one register. 10446 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S)) 10447 return ReplacedZeroSplat; 10448 10449 // FIXME: The logic for deciding if an unaligned store should be split should 10450 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be 10451 // a call to that function here. 10452 10453 if (!Subtarget->isMisaligned128StoreSlow()) 10454 return SDValue(); 10455 10456 // Don't split at -Oz. 10457 if (DAG.getMachineFunction().getFunction().hasMinSize()) 10458 return SDValue(); 10459 10460 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting 10461 // those up regresses performance on micro-benchmarks and olden/bh. 10462 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64) 10463 return SDValue(); 10464 10465 // Split unaligned 16B stores. They are terrible for performance. 10466 // Don't split stores with alignment of 1 or 2. Code that uses clang vector 10467 // extensions can use this to mark that it does not want splitting to happen 10468 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of 10469 // eliminating alignment hazards is only 1 in 8 for alignment of 2. 10470 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 || 10471 S->getAlignment() <= 2) 10472 return SDValue(); 10473 10474 // If we get a splat of a scalar convert this vector store to a store of 10475 // scalars. They will be merged into store pairs thereby removing two 10476 // instructions. 10477 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S)) 10478 return ReplacedSplat; 10479 10480 SDLoc DL(S); 10481 unsigned NumElts = VT.getVectorNumElements() / 2; 10482 // Split VT into two. 10483 EVT HalfVT = 10484 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts); 10485 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 10486 DAG.getConstant(0, DL, MVT::i64)); 10487 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal, 10488 DAG.getConstant(NumElts, DL, MVT::i64)); 10489 SDValue BasePtr = S->getBasePtr(); 10490 SDValue NewST1 = 10491 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(), 10492 S->getAlignment(), S->getMemOperand()->getFlags()); 10493 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr, 10494 DAG.getConstant(8, DL, MVT::i64)); 10495 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr, 10496 S->getPointerInfo(), S->getAlignment(), 10497 S->getMemOperand()->getFlags()); 10498 } 10499 10500 /// Target-specific DAG combine function for post-increment LD1 (lane) and 10501 /// post-increment LD1R. 10502 static SDValue performPostLD1Combine(SDNode *N, 10503 TargetLowering::DAGCombinerInfo &DCI, 10504 bool IsLaneOp) { 10505 if (DCI.isBeforeLegalizeOps()) 10506 return SDValue(); 10507 10508 SelectionDAG &DAG = DCI.DAG; 10509 EVT VT = N->getValueType(0); 10510 10511 unsigned LoadIdx = IsLaneOp ? 1 : 0; 10512 SDNode *LD = N->getOperand(LoadIdx).getNode(); 10513 // If it is not LOAD, can not do such combine. 10514 if (LD->getOpcode() != ISD::LOAD) 10515 return SDValue(); 10516 10517 // The vector lane must be a constant in the LD1LANE opcode. 10518 SDValue Lane; 10519 if (IsLaneOp) { 10520 Lane = N->getOperand(2); 10521 auto *LaneC = dyn_cast<ConstantSDNode>(Lane); 10522 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements()) 10523 return SDValue(); 10524 } 10525 10526 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD); 10527 EVT MemVT = LoadSDN->getMemoryVT(); 10528 // Check if memory operand is the same type as the vector element. 10529 if (MemVT != VT.getVectorElementType()) 10530 return SDValue(); 10531 10532 // Check if there are other uses. If so, do not combine as it will introduce 10533 // an extra load. 10534 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE; 10535 ++UI) { 10536 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result. 10537 continue; 10538 if (*UI != N) 10539 return SDValue(); 10540 } 10541 10542 SDValue Addr = LD->getOperand(1); 10543 SDValue Vector = N->getOperand(0); 10544 // Search for a use of the address operand that is an increment. 10545 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE = 10546 Addr.getNode()->use_end(); UI != UE; ++UI) { 10547 SDNode *User = *UI; 10548 if (User->getOpcode() != ISD::ADD 10549 || UI.getUse().getResNo() != Addr.getResNo()) 10550 continue; 10551 10552 // If the increment is a constant, it must match the memory ref size. 10553 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 10554 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 10555 uint32_t IncVal = CInc->getZExtValue(); 10556 unsigned NumBytes = VT.getScalarSizeInBits() / 8; 10557 if (IncVal != NumBytes) 10558 continue; 10559 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 10560 } 10561 10562 // To avoid cycle construction make sure that neither the load nor the add 10563 // are predecessors to each other or the Vector. 10564 SmallPtrSet<const SDNode *, 32> Visited; 10565 SmallVector<const SDNode *, 16> Worklist; 10566 Visited.insert(N); 10567 Worklist.push_back(User); 10568 Worklist.push_back(LD); 10569 Worklist.push_back(Vector.getNode()); 10570 if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) || 10571 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 10572 continue; 10573 10574 SmallVector<SDValue, 8> Ops; 10575 Ops.push_back(LD->getOperand(0)); // Chain 10576 if (IsLaneOp) { 10577 Ops.push_back(Vector); // The vector to be inserted 10578 Ops.push_back(Lane); // The lane to be inserted in the vector 10579 } 10580 Ops.push_back(Addr); 10581 Ops.push_back(Inc); 10582 10583 EVT Tys[3] = { VT, MVT::i64, MVT::Other }; 10584 SDVTList SDTys = DAG.getVTList(Tys); 10585 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost; 10586 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops, 10587 MemVT, 10588 LoadSDN->getMemOperand()); 10589 10590 // Update the uses. 10591 SDValue NewResults[] = { 10592 SDValue(LD, 0), // The result of load 10593 SDValue(UpdN.getNode(), 2) // Chain 10594 }; 10595 DCI.CombineTo(LD, NewResults); 10596 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result 10597 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register 10598 10599 break; 10600 } 10601 return SDValue(); 10602 } 10603 10604 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during 10605 /// address translation. 10606 static bool performTBISimplification(SDValue Addr, 10607 TargetLowering::DAGCombinerInfo &DCI, 10608 SelectionDAG &DAG) { 10609 APInt DemandedMask = APInt::getLowBitsSet(64, 56); 10610 KnownBits Known; 10611 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(), 10612 !DCI.isBeforeLegalizeOps()); 10613 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 10614 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) { 10615 DCI.CommitTargetLoweringOpt(TLO); 10616 return true; 10617 } 10618 return false; 10619 } 10620 10621 static SDValue performSTORECombine(SDNode *N, 10622 TargetLowering::DAGCombinerInfo &DCI, 10623 SelectionDAG &DAG, 10624 const AArch64Subtarget *Subtarget) { 10625 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget)) 10626 return Split; 10627 10628 if (Subtarget->supportsAddressTopByteIgnored() && 10629 performTBISimplification(N->getOperand(2), DCI, DAG)) 10630 return SDValue(N, 0); 10631 10632 return SDValue(); 10633 } 10634 10635 10636 /// Target-specific DAG combine function for NEON load/store intrinsics 10637 /// to merge base address updates. 10638 static SDValue performNEONPostLDSTCombine(SDNode *N, 10639 TargetLowering::DAGCombinerInfo &DCI, 10640 SelectionDAG &DAG) { 10641 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer()) 10642 return SDValue(); 10643 10644 unsigned AddrOpIdx = N->getNumOperands() - 1; 10645 SDValue Addr = N->getOperand(AddrOpIdx); 10646 10647 // Search for a use of the address operand that is an increment. 10648 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), 10649 UE = Addr.getNode()->use_end(); UI != UE; ++UI) { 10650 SDNode *User = *UI; 10651 if (User->getOpcode() != ISD::ADD || 10652 UI.getUse().getResNo() != Addr.getResNo()) 10653 continue; 10654 10655 // Check that the add is independent of the load/store. Otherwise, folding 10656 // it would create a cycle. 10657 SmallPtrSet<const SDNode *, 32> Visited; 10658 SmallVector<const SDNode *, 16> Worklist; 10659 Visited.insert(Addr.getNode()); 10660 Worklist.push_back(N); 10661 Worklist.push_back(User); 10662 if (SDNode::hasPredecessorHelper(N, Visited, Worklist) || 10663 SDNode::hasPredecessorHelper(User, Visited, Worklist)) 10664 continue; 10665 10666 // Find the new opcode for the updating load/store. 10667 bool IsStore = false; 10668 bool IsLaneOp = false; 10669 bool IsDupOp = false; 10670 unsigned NewOpc = 0; 10671 unsigned NumVecs = 0; 10672 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 10673 switch (IntNo) { 10674 default: llvm_unreachable("unexpected intrinsic for Neon base update"); 10675 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post; 10676 NumVecs = 2; break; 10677 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post; 10678 NumVecs = 3; break; 10679 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post; 10680 NumVecs = 4; break; 10681 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post; 10682 NumVecs = 2; IsStore = true; break; 10683 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post; 10684 NumVecs = 3; IsStore = true; break; 10685 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post; 10686 NumVecs = 4; IsStore = true; break; 10687 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post; 10688 NumVecs = 2; break; 10689 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post; 10690 NumVecs = 3; break; 10691 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post; 10692 NumVecs = 4; break; 10693 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post; 10694 NumVecs = 2; IsStore = true; break; 10695 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post; 10696 NumVecs = 3; IsStore = true; break; 10697 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post; 10698 NumVecs = 4; IsStore = true; break; 10699 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost; 10700 NumVecs = 2; IsDupOp = true; break; 10701 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost; 10702 NumVecs = 3; IsDupOp = true; break; 10703 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost; 10704 NumVecs = 4; IsDupOp = true; break; 10705 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost; 10706 NumVecs = 2; IsLaneOp = true; break; 10707 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost; 10708 NumVecs = 3; IsLaneOp = true; break; 10709 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost; 10710 NumVecs = 4; IsLaneOp = true; break; 10711 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost; 10712 NumVecs = 2; IsStore = true; IsLaneOp = true; break; 10713 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost; 10714 NumVecs = 3; IsStore = true; IsLaneOp = true; break; 10715 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost; 10716 NumVecs = 4; IsStore = true; IsLaneOp = true; break; 10717 } 10718 10719 EVT VecTy; 10720 if (IsStore) 10721 VecTy = N->getOperand(2).getValueType(); 10722 else 10723 VecTy = N->getValueType(0); 10724 10725 // If the increment is a constant, it must match the memory ref size. 10726 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0); 10727 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) { 10728 uint32_t IncVal = CInc->getZExtValue(); 10729 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8; 10730 if (IsLaneOp || IsDupOp) 10731 NumBytes /= VecTy.getVectorNumElements(); 10732 if (IncVal != NumBytes) 10733 continue; 10734 Inc = DAG.getRegister(AArch64::XZR, MVT::i64); 10735 } 10736 SmallVector<SDValue, 8> Ops; 10737 Ops.push_back(N->getOperand(0)); // Incoming chain 10738 // Load lane and store have vector list as input. 10739 if (IsLaneOp || IsStore) 10740 for (unsigned i = 2; i < AddrOpIdx; ++i) 10741 Ops.push_back(N->getOperand(i)); 10742 Ops.push_back(Addr); // Base register 10743 Ops.push_back(Inc); 10744 10745 // Return Types. 10746 EVT Tys[6]; 10747 unsigned NumResultVecs = (IsStore ? 0 : NumVecs); 10748 unsigned n; 10749 for (n = 0; n < NumResultVecs; ++n) 10750 Tys[n] = VecTy; 10751 Tys[n++] = MVT::i64; // Type of write back register 10752 Tys[n] = MVT::Other; // Type of the chain 10753 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2)); 10754 10755 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N); 10756 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops, 10757 MemInt->getMemoryVT(), 10758 MemInt->getMemOperand()); 10759 10760 // Update the uses. 10761 std::vector<SDValue> NewResults; 10762 for (unsigned i = 0; i < NumResultVecs; ++i) { 10763 NewResults.push_back(SDValue(UpdN.getNode(), i)); 10764 } 10765 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); 10766 DCI.CombineTo(N, NewResults); 10767 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs)); 10768 10769 break; 10770 } 10771 return SDValue(); 10772 } 10773 10774 // Checks to see if the value is the prescribed width and returns information 10775 // about its extension mode. 10776 static 10777 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) { 10778 ExtType = ISD::NON_EXTLOAD; 10779 switch(V.getNode()->getOpcode()) { 10780 default: 10781 return false; 10782 case ISD::LOAD: { 10783 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode()); 10784 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8) 10785 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) { 10786 ExtType = LoadNode->getExtensionType(); 10787 return true; 10788 } 10789 return false; 10790 } 10791 case ISD::AssertSext: { 10792 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 10793 if ((TypeNode->getVT() == MVT::i8 && width == 8) 10794 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 10795 ExtType = ISD::SEXTLOAD; 10796 return true; 10797 } 10798 return false; 10799 } 10800 case ISD::AssertZext: { 10801 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1)); 10802 if ((TypeNode->getVT() == MVT::i8 && width == 8) 10803 || (TypeNode->getVT() == MVT::i16 && width == 16)) { 10804 ExtType = ISD::ZEXTLOAD; 10805 return true; 10806 } 10807 return false; 10808 } 10809 case ISD::Constant: 10810 case ISD::TargetConstant: { 10811 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) < 10812 1LL << (width - 1); 10813 } 10814 } 10815 10816 return true; 10817 } 10818 10819 // This function does a whole lot of voodoo to determine if the tests are 10820 // equivalent without and with a mask. Essentially what happens is that given a 10821 // DAG resembling: 10822 // 10823 // +-------------+ +-------------+ +-------------+ +-------------+ 10824 // | Input | | AddConstant | | CompConstant| | CC | 10825 // +-------------+ +-------------+ +-------------+ +-------------+ 10826 // | | | | 10827 // V V | +----------+ 10828 // +-------------+ +----+ | | 10829 // | ADD | |0xff| | | 10830 // +-------------+ +----+ | | 10831 // | | | | 10832 // V V | | 10833 // +-------------+ | | 10834 // | AND | | | 10835 // +-------------+ | | 10836 // | | | 10837 // +-----+ | | 10838 // | | | 10839 // V V V 10840 // +-------------+ 10841 // | CMP | 10842 // +-------------+ 10843 // 10844 // The AND node may be safely removed for some combinations of inputs. In 10845 // particular we need to take into account the extension type of the Input, 10846 // the exact values of AddConstant, CompConstant, and CC, along with the nominal 10847 // width of the input (this can work for any width inputs, the above graph is 10848 // specific to 8 bits. 10849 // 10850 // The specific equations were worked out by generating output tables for each 10851 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The 10852 // problem was simplified by working with 4 bit inputs, which means we only 10853 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero 10854 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8 10855 // patterns present in both extensions (0,7). For every distinct set of 10856 // AddConstant and CompConstants bit patterns we can consider the masked and 10857 // unmasked versions to be equivalent if the result of this function is true for 10858 // all 16 distinct bit patterns of for the current extension type of Input (w0). 10859 // 10860 // sub w8, w0, w1 10861 // and w10, w8, #0x0f 10862 // cmp w8, w2 10863 // cset w9, AArch64CC 10864 // cmp w10, w2 10865 // cset w11, AArch64CC 10866 // cmp w9, w11 10867 // cset w0, eq 10868 // ret 10869 // 10870 // Since the above function shows when the outputs are equivalent it defines 10871 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and 10872 // would be expensive to run during compiles. The equations below were written 10873 // in a test harness that confirmed they gave equivalent outputs to the above 10874 // for all inputs function, so they can be used determine if the removal is 10875 // legal instead. 10876 // 10877 // isEquivalentMaskless() is the code for testing if the AND can be removed 10878 // factored out of the DAG recognition as the DAG can take several forms. 10879 10880 static bool isEquivalentMaskless(unsigned CC, unsigned width, 10881 ISD::LoadExtType ExtType, int AddConstant, 10882 int CompConstant) { 10883 // By being careful about our equations and only writing the in term 10884 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can 10885 // make them generally applicable to all bit widths. 10886 int MaxUInt = (1 << width); 10887 10888 // For the purposes of these comparisons sign extending the type is 10889 // equivalent to zero extending the add and displacing it by half the integer 10890 // width. Provided we are careful and make sure our equations are valid over 10891 // the whole range we can just adjust the input and avoid writing equations 10892 // for sign extended inputs. 10893 if (ExtType == ISD::SEXTLOAD) 10894 AddConstant -= (1 << (width-1)); 10895 10896 switch(CC) { 10897 case AArch64CC::LE: 10898 case AArch64CC::GT: 10899 if ((AddConstant == 0) || 10900 (CompConstant == MaxUInt - 1 && AddConstant < 0) || 10901 (AddConstant >= 0 && CompConstant < 0) || 10902 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant)) 10903 return true; 10904 break; 10905 case AArch64CC::LT: 10906 case AArch64CC::GE: 10907 if ((AddConstant == 0) || 10908 (AddConstant >= 0 && CompConstant <= 0) || 10909 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant)) 10910 return true; 10911 break; 10912 case AArch64CC::HI: 10913 case AArch64CC::LS: 10914 if ((AddConstant >= 0 && CompConstant < 0) || 10915 (AddConstant <= 0 && CompConstant >= -1 && 10916 CompConstant < AddConstant + MaxUInt)) 10917 return true; 10918 break; 10919 case AArch64CC::PL: 10920 case AArch64CC::MI: 10921 if ((AddConstant == 0) || 10922 (AddConstant > 0 && CompConstant <= 0) || 10923 (AddConstant < 0 && CompConstant <= AddConstant)) 10924 return true; 10925 break; 10926 case AArch64CC::LO: 10927 case AArch64CC::HS: 10928 if ((AddConstant >= 0 && CompConstant <= 0) || 10929 (AddConstant <= 0 && CompConstant >= 0 && 10930 CompConstant <= AddConstant + MaxUInt)) 10931 return true; 10932 break; 10933 case AArch64CC::EQ: 10934 case AArch64CC::NE: 10935 if ((AddConstant > 0 && CompConstant < 0) || 10936 (AddConstant < 0 && CompConstant >= 0 && 10937 CompConstant < AddConstant + MaxUInt) || 10938 (AddConstant >= 0 && CompConstant >= 0 && 10939 CompConstant >= AddConstant) || 10940 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant)) 10941 return true; 10942 break; 10943 case AArch64CC::VS: 10944 case AArch64CC::VC: 10945 case AArch64CC::AL: 10946 case AArch64CC::NV: 10947 return true; 10948 case AArch64CC::Invalid: 10949 break; 10950 } 10951 10952 return false; 10953 } 10954 10955 static 10956 SDValue performCONDCombine(SDNode *N, 10957 TargetLowering::DAGCombinerInfo &DCI, 10958 SelectionDAG &DAG, unsigned CCIndex, 10959 unsigned CmpIndex) { 10960 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue(); 10961 SDNode *SubsNode = N->getOperand(CmpIndex).getNode(); 10962 unsigned CondOpcode = SubsNode->getOpcode(); 10963 10964 if (CondOpcode != AArch64ISD::SUBS) 10965 return SDValue(); 10966 10967 // There is a SUBS feeding this condition. Is it fed by a mask we can 10968 // use? 10969 10970 SDNode *AndNode = SubsNode->getOperand(0).getNode(); 10971 unsigned MaskBits = 0; 10972 10973 if (AndNode->getOpcode() != ISD::AND) 10974 return SDValue(); 10975 10976 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) { 10977 uint32_t CNV = CN->getZExtValue(); 10978 if (CNV == 255) 10979 MaskBits = 8; 10980 else if (CNV == 65535) 10981 MaskBits = 16; 10982 } 10983 10984 if (!MaskBits) 10985 return SDValue(); 10986 10987 SDValue AddValue = AndNode->getOperand(0); 10988 10989 if (AddValue.getOpcode() != ISD::ADD) 10990 return SDValue(); 10991 10992 // The basic dag structure is correct, grab the inputs and validate them. 10993 10994 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0); 10995 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1); 10996 SDValue SubsInputValue = SubsNode->getOperand(1); 10997 10998 // The mask is present and the provenance of all the values is a smaller type, 10999 // lets see if the mask is superfluous. 11000 11001 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) || 11002 !isa<ConstantSDNode>(SubsInputValue.getNode())) 11003 return SDValue(); 11004 11005 ISD::LoadExtType ExtType; 11006 11007 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) || 11008 !checkValueWidth(AddInputValue2, MaskBits, ExtType) || 11009 !checkValueWidth(AddInputValue1, MaskBits, ExtType) ) 11010 return SDValue(); 11011 11012 if(!isEquivalentMaskless(CC, MaskBits, ExtType, 11013 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(), 11014 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue())) 11015 return SDValue(); 11016 11017 // The AND is not necessary, remove it. 11018 11019 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0), 11020 SubsNode->getValueType(1)); 11021 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) }; 11022 11023 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops); 11024 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode()); 11025 11026 return SDValue(N, 0); 11027 } 11028 11029 // Optimize compare with zero and branch. 11030 static SDValue performBRCONDCombine(SDNode *N, 11031 TargetLowering::DAGCombinerInfo &DCI, 11032 SelectionDAG &DAG) { 11033 MachineFunction &MF = DAG.getMachineFunction(); 11034 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions 11035 // will not be produced, as they are conditional branch instructions that do 11036 // not set flags. 11037 if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening)) 11038 return SDValue(); 11039 11040 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3)) 11041 N = NV.getNode(); 11042 SDValue Chain = N->getOperand(0); 11043 SDValue Dest = N->getOperand(1); 11044 SDValue CCVal = N->getOperand(2); 11045 SDValue Cmp = N->getOperand(3); 11046 11047 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!"); 11048 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue(); 11049 if (CC != AArch64CC::EQ && CC != AArch64CC::NE) 11050 return SDValue(); 11051 11052 unsigned CmpOpc = Cmp.getOpcode(); 11053 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS) 11054 return SDValue(); 11055 11056 // Only attempt folding if there is only one use of the flag and no use of the 11057 // value. 11058 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1)) 11059 return SDValue(); 11060 11061 SDValue LHS = Cmp.getOperand(0); 11062 SDValue RHS = Cmp.getOperand(1); 11063 11064 assert(LHS.getValueType() == RHS.getValueType() && 11065 "Expected the value type to be the same for both operands!"); 11066 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64) 11067 return SDValue(); 11068 11069 if (isNullConstant(LHS)) 11070 std::swap(LHS, RHS); 11071 11072 if (!isNullConstant(RHS)) 11073 return SDValue(); 11074 11075 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA || 11076 LHS.getOpcode() == ISD::SRL) 11077 return SDValue(); 11078 11079 // Fold the compare into the branch instruction. 11080 SDValue BR; 11081 if (CC == AArch64CC::EQ) 11082 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 11083 else 11084 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest); 11085 11086 // Do not add new nodes to DAG combiner worklist. 11087 DCI.CombineTo(N, BR, false); 11088 11089 return SDValue(); 11090 } 11091 11092 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test 11093 // as well as whether the test should be inverted. This code is required to 11094 // catch these cases (as opposed to standard dag combines) because 11095 // AArch64ISD::TBZ is matched during legalization. 11096 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert, 11097 SelectionDAG &DAG) { 11098 11099 if (!Op->hasOneUse()) 11100 return Op; 11101 11102 // We don't handle undef/constant-fold cases below, as they should have 11103 // already been taken care of (e.g. and of 0, test of undefined shifted bits, 11104 // etc.) 11105 11106 // (tbz (trunc x), b) -> (tbz x, b) 11107 // This case is just here to enable more of the below cases to be caught. 11108 if (Op->getOpcode() == ISD::TRUNCATE && 11109 Bit < Op->getValueType(0).getSizeInBits()) { 11110 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 11111 } 11112 11113 // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits. 11114 if (Op->getOpcode() == ISD::ANY_EXTEND && 11115 Bit < Op->getOperand(0).getValueSizeInBits()) { 11116 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 11117 } 11118 11119 if (Op->getNumOperands() != 2) 11120 return Op; 11121 11122 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1)); 11123 if (!C) 11124 return Op; 11125 11126 switch (Op->getOpcode()) { 11127 default: 11128 return Op; 11129 11130 // (tbz (and x, m), b) -> (tbz x, b) 11131 case ISD::AND: 11132 if ((C->getZExtValue() >> Bit) & 1) 11133 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 11134 return Op; 11135 11136 // (tbz (shl x, c), b) -> (tbz x, b-c) 11137 case ISD::SHL: 11138 if (C->getZExtValue() <= Bit && 11139 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 11140 Bit = Bit - C->getZExtValue(); 11141 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 11142 } 11143 return Op; 11144 11145 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x 11146 case ISD::SRA: 11147 Bit = Bit + C->getZExtValue(); 11148 if (Bit >= Op->getValueType(0).getSizeInBits()) 11149 Bit = Op->getValueType(0).getSizeInBits() - 1; 11150 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 11151 11152 // (tbz (srl x, c), b) -> (tbz x, b+c) 11153 case ISD::SRL: 11154 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) { 11155 Bit = Bit + C->getZExtValue(); 11156 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 11157 } 11158 return Op; 11159 11160 // (tbz (xor x, -1), b) -> (tbnz x, b) 11161 case ISD::XOR: 11162 if ((C->getZExtValue() >> Bit) & 1) 11163 Invert = !Invert; 11164 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG); 11165 } 11166 } 11167 11168 // Optimize test single bit zero/non-zero and branch. 11169 static SDValue performTBZCombine(SDNode *N, 11170 TargetLowering::DAGCombinerInfo &DCI, 11171 SelectionDAG &DAG) { 11172 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(); 11173 bool Invert = false; 11174 SDValue TestSrc = N->getOperand(1); 11175 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG); 11176 11177 if (TestSrc == NewTestSrc) 11178 return SDValue(); 11179 11180 unsigned NewOpc = N->getOpcode(); 11181 if (Invert) { 11182 if (NewOpc == AArch64ISD::TBZ) 11183 NewOpc = AArch64ISD::TBNZ; 11184 else { 11185 assert(NewOpc == AArch64ISD::TBNZ); 11186 NewOpc = AArch64ISD::TBZ; 11187 } 11188 } 11189 11190 SDLoc DL(N); 11191 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc, 11192 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3)); 11193 } 11194 11195 // vselect (v1i1 setcc) -> 11196 // vselect (v1iXX setcc) (XX is the size of the compared operand type) 11197 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as 11198 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine 11199 // such VSELECT. 11200 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) { 11201 SDValue N0 = N->getOperand(0); 11202 EVT CCVT = N0.getValueType(); 11203 11204 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 || 11205 CCVT.getVectorElementType() != MVT::i1) 11206 return SDValue(); 11207 11208 EVT ResVT = N->getValueType(0); 11209 EVT CmpVT = N0.getOperand(0).getValueType(); 11210 // Only combine when the result type is of the same size as the compared 11211 // operands. 11212 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits()) 11213 return SDValue(); 11214 11215 SDValue IfTrue = N->getOperand(1); 11216 SDValue IfFalse = N->getOperand(2); 11217 SDValue SetCC = 11218 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(), 11219 N0.getOperand(0), N0.getOperand(1), 11220 cast<CondCodeSDNode>(N0.getOperand(2))->get()); 11221 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC, 11222 IfTrue, IfFalse); 11223 } 11224 11225 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with 11226 /// the compare-mask instructions rather than going via NZCV, even if LHS and 11227 /// RHS are really scalar. This replaces any scalar setcc in the above pattern 11228 /// with a vector one followed by a DUP shuffle on the result. 11229 static SDValue performSelectCombine(SDNode *N, 11230 TargetLowering::DAGCombinerInfo &DCI) { 11231 SelectionDAG &DAG = DCI.DAG; 11232 SDValue N0 = N->getOperand(0); 11233 EVT ResVT = N->getValueType(0); 11234 11235 if (N0.getOpcode() != ISD::SETCC) 11236 return SDValue(); 11237 11238 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered 11239 // scalar SetCCResultType. We also don't expect vectors, because we assume 11240 // that selects fed by vector SETCCs are canonicalized to VSELECT. 11241 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) && 11242 "Scalar-SETCC feeding SELECT has unexpected result type!"); 11243 11244 // If NumMaskElts == 0, the comparison is larger than select result. The 11245 // largest real NEON comparison is 64-bits per lane, which means the result is 11246 // at most 32-bits and an illegal vector. Just bail out for now. 11247 EVT SrcVT = N0.getOperand(0).getValueType(); 11248 11249 // Don't try to do this optimization when the setcc itself has i1 operands. 11250 // There are no legal vectors of i1, so this would be pointless. 11251 if (SrcVT == MVT::i1) 11252 return SDValue(); 11253 11254 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits(); 11255 if (!ResVT.isVector() || NumMaskElts == 0) 11256 return SDValue(); 11257 11258 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts); 11259 EVT CCVT = SrcVT.changeVectorElementTypeToInteger(); 11260 11261 // Also bail out if the vector CCVT isn't the same size as ResVT. 11262 // This can happen if the SETCC operand size doesn't divide the ResVT size 11263 // (e.g., f64 vs v3f32). 11264 if (CCVT.getSizeInBits() != ResVT.getSizeInBits()) 11265 return SDValue(); 11266 11267 // Make sure we didn't create illegal types, if we're not supposed to. 11268 assert(DCI.isBeforeLegalize() || 11269 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT)); 11270 11271 // First perform a vector comparison, where lane 0 is the one we're interested 11272 // in. 11273 SDLoc DL(N0); 11274 SDValue LHS = 11275 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0)); 11276 SDValue RHS = 11277 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1)); 11278 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2)); 11279 11280 // Now duplicate the comparison mask we want across all other lanes. 11281 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0); 11282 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask); 11283 Mask = DAG.getNode(ISD::BITCAST, DL, 11284 ResVT.changeVectorElementTypeToInteger(), Mask); 11285 11286 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2)); 11287 } 11288 11289 /// Get rid of unnecessary NVCASTs (that don't change the type). 11290 static SDValue performNVCASTCombine(SDNode *N) { 11291 if (N->getValueType(0) == N->getOperand(0).getValueType()) 11292 return N->getOperand(0); 11293 11294 return SDValue(); 11295 } 11296 11297 // If all users of the globaladdr are of the form (globaladdr + constant), find 11298 // the smallest constant, fold it into the globaladdr's offset and rewrite the 11299 // globaladdr as (globaladdr + constant) - constant. 11300 static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG, 11301 const AArch64Subtarget *Subtarget, 11302 const TargetMachine &TM) { 11303 auto *GN = cast<GlobalAddressSDNode>(N); 11304 if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) != 11305 AArch64II::MO_NO_FLAG) 11306 return SDValue(); 11307 11308 uint64_t MinOffset = -1ull; 11309 for (SDNode *N : GN->uses()) { 11310 if (N->getOpcode() != ISD::ADD) 11311 return SDValue(); 11312 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0)); 11313 if (!C) 11314 C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 11315 if (!C) 11316 return SDValue(); 11317 MinOffset = std::min(MinOffset, C->getZExtValue()); 11318 } 11319 uint64_t Offset = MinOffset + GN->getOffset(); 11320 11321 // Require that the new offset is larger than the existing one. Otherwise, we 11322 // can end up oscillating between two possible DAGs, for example, 11323 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1). 11324 if (Offset <= uint64_t(GN->getOffset())) 11325 return SDValue(); 11326 11327 // Check whether folding this offset is legal. It must not go out of bounds of 11328 // the referenced object to avoid violating the code model, and must be 11329 // smaller than 2^21 because this is the largest offset expressible in all 11330 // object formats. 11331 // 11332 // This check also prevents us from folding negative offsets, which will end 11333 // up being treated in the same way as large positive ones. They could also 11334 // cause code model violations, and aren't really common enough to matter. 11335 if (Offset >= (1 << 21)) 11336 return SDValue(); 11337 11338 const GlobalValue *GV = GN->getGlobal(); 11339 Type *T = GV->getValueType(); 11340 if (!T->isSized() || 11341 Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T)) 11342 return SDValue(); 11343 11344 SDLoc DL(GN); 11345 SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset); 11346 return DAG.getNode(ISD::SUB, DL, MVT::i64, Result, 11347 DAG.getConstant(MinOffset, DL, MVT::i64)); 11348 } 11349 11350 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N, 11351 DAGCombinerInfo &DCI) const { 11352 SelectionDAG &DAG = DCI.DAG; 11353 switch (N->getOpcode()) { 11354 default: 11355 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n"); 11356 break; 11357 case ISD::ADD: 11358 case ISD::SUB: 11359 return performAddSubLongCombine(N, DCI, DAG); 11360 case ISD::XOR: 11361 return performXorCombine(N, DAG, DCI, Subtarget); 11362 case ISD::MUL: 11363 return performMulCombine(N, DAG, DCI, Subtarget); 11364 case ISD::SINT_TO_FP: 11365 case ISD::UINT_TO_FP: 11366 return performIntToFpCombine(N, DAG, Subtarget); 11367 case ISD::FP_TO_SINT: 11368 case ISD::FP_TO_UINT: 11369 return performFpToIntCombine(N, DAG, DCI, Subtarget); 11370 case ISD::FDIV: 11371 return performFDivCombine(N, DAG, DCI, Subtarget); 11372 case ISD::OR: 11373 return performORCombine(N, DCI, Subtarget); 11374 case ISD::AND: 11375 return performANDCombine(N, DCI); 11376 case ISD::SRL: 11377 return performSRLCombine(N, DCI); 11378 case ISD::INTRINSIC_WO_CHAIN: 11379 return performIntrinsicCombine(N, DCI, Subtarget); 11380 case ISD::ANY_EXTEND: 11381 case ISD::ZERO_EXTEND: 11382 case ISD::SIGN_EXTEND: 11383 return performExtendCombine(N, DCI, DAG); 11384 case ISD::BITCAST: 11385 return performBitcastCombine(N, DCI, DAG); 11386 case ISD::CONCAT_VECTORS: 11387 return performConcatVectorsCombine(N, DCI, DAG); 11388 case ISD::SELECT: 11389 return performSelectCombine(N, DCI); 11390 case ISD::VSELECT: 11391 return performVSelectCombine(N, DCI.DAG); 11392 case ISD::LOAD: 11393 if (performTBISimplification(N->getOperand(1), DCI, DAG)) 11394 return SDValue(N, 0); 11395 break; 11396 case ISD::STORE: 11397 return performSTORECombine(N, DCI, DAG, Subtarget); 11398 case AArch64ISD::BRCOND: 11399 return performBRCONDCombine(N, DCI, DAG); 11400 case AArch64ISD::TBNZ: 11401 case AArch64ISD::TBZ: 11402 return performTBZCombine(N, DCI, DAG); 11403 case AArch64ISD::CSEL: 11404 return performCONDCombine(N, DCI, DAG, 2, 3); 11405 case AArch64ISD::DUP: 11406 return performPostLD1Combine(N, DCI, false); 11407 case AArch64ISD::NVCAST: 11408 return performNVCASTCombine(N); 11409 case ISD::INSERT_VECTOR_ELT: 11410 return performPostLD1Combine(N, DCI, true); 11411 case ISD::INTRINSIC_VOID: 11412 case ISD::INTRINSIC_W_CHAIN: 11413 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) { 11414 case Intrinsic::aarch64_neon_ld2: 11415 case Intrinsic::aarch64_neon_ld3: 11416 case Intrinsic::aarch64_neon_ld4: 11417 case Intrinsic::aarch64_neon_ld1x2: 11418 case Intrinsic::aarch64_neon_ld1x3: 11419 case Intrinsic::aarch64_neon_ld1x4: 11420 case Intrinsic::aarch64_neon_ld2lane: 11421 case Intrinsic::aarch64_neon_ld3lane: 11422 case Intrinsic::aarch64_neon_ld4lane: 11423 case Intrinsic::aarch64_neon_ld2r: 11424 case Intrinsic::aarch64_neon_ld3r: 11425 case Intrinsic::aarch64_neon_ld4r: 11426 case Intrinsic::aarch64_neon_st2: 11427 case Intrinsic::aarch64_neon_st3: 11428 case Intrinsic::aarch64_neon_st4: 11429 case Intrinsic::aarch64_neon_st1x2: 11430 case Intrinsic::aarch64_neon_st1x3: 11431 case Intrinsic::aarch64_neon_st1x4: 11432 case Intrinsic::aarch64_neon_st2lane: 11433 case Intrinsic::aarch64_neon_st3lane: 11434 case Intrinsic::aarch64_neon_st4lane: 11435 return performNEONPostLDSTCombine(N, DCI, DAG); 11436 default: 11437 break; 11438 } 11439 break; 11440 case ISD::GlobalAddress: 11441 return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine()); 11442 } 11443 return SDValue(); 11444 } 11445 11446 // Check if the return value is used as only a return value, as otherwise 11447 // we can't perform a tail-call. In particular, we need to check for 11448 // target ISD nodes that are returns and any other "odd" constructs 11449 // that the generic analysis code won't necessarily catch. 11450 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N, 11451 SDValue &Chain) const { 11452 if (N->getNumValues() != 1) 11453 return false; 11454 if (!N->hasNUsesOfValue(1, 0)) 11455 return false; 11456 11457 SDValue TCChain = Chain; 11458 SDNode *Copy = *N->use_begin(); 11459 if (Copy->getOpcode() == ISD::CopyToReg) { 11460 // If the copy has a glue operand, we conservatively assume it isn't safe to 11461 // perform a tail call. 11462 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() == 11463 MVT::Glue) 11464 return false; 11465 TCChain = Copy->getOperand(0); 11466 } else if (Copy->getOpcode() != ISD::FP_EXTEND) 11467 return false; 11468 11469 bool HasRet = false; 11470 for (SDNode *Node : Copy->uses()) { 11471 if (Node->getOpcode() != AArch64ISD::RET_FLAG) 11472 return false; 11473 HasRet = true; 11474 } 11475 11476 if (!HasRet) 11477 return false; 11478 11479 Chain = TCChain; 11480 return true; 11481 } 11482 11483 // Return whether the an instruction can potentially be optimized to a tail 11484 // call. This will cause the optimizers to attempt to move, or duplicate, 11485 // return instructions to help enable tail call optimizations for this 11486 // instruction. 11487 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 11488 return CI->isTailCall(); 11489 } 11490 11491 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base, 11492 SDValue &Offset, 11493 ISD::MemIndexedMode &AM, 11494 bool &IsInc, 11495 SelectionDAG &DAG) const { 11496 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB) 11497 return false; 11498 11499 Base = Op->getOperand(0); 11500 // All of the indexed addressing mode instructions take a signed 11501 // 9 bit immediate offset. 11502 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) { 11503 int64_t RHSC = RHS->getSExtValue(); 11504 if (Op->getOpcode() == ISD::SUB) 11505 RHSC = -(uint64_t)RHSC; 11506 if (!isInt<9>(RHSC)) 11507 return false; 11508 IsInc = (Op->getOpcode() == ISD::ADD); 11509 Offset = Op->getOperand(1); 11510 return true; 11511 } 11512 return false; 11513 } 11514 11515 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base, 11516 SDValue &Offset, 11517 ISD::MemIndexedMode &AM, 11518 SelectionDAG &DAG) const { 11519 EVT VT; 11520 SDValue Ptr; 11521 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11522 VT = LD->getMemoryVT(); 11523 Ptr = LD->getBasePtr(); 11524 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11525 VT = ST->getMemoryVT(); 11526 Ptr = ST->getBasePtr(); 11527 } else 11528 return false; 11529 11530 bool IsInc; 11531 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG)) 11532 return false; 11533 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC; 11534 return true; 11535 } 11536 11537 bool AArch64TargetLowering::getPostIndexedAddressParts( 11538 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset, 11539 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const { 11540 EVT VT; 11541 SDValue Ptr; 11542 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) { 11543 VT = LD->getMemoryVT(); 11544 Ptr = LD->getBasePtr(); 11545 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) { 11546 VT = ST->getMemoryVT(); 11547 Ptr = ST->getBasePtr(); 11548 } else 11549 return false; 11550 11551 bool IsInc; 11552 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG)) 11553 return false; 11554 // Post-indexing updates the base, so it's not a valid transform 11555 // if that's not the same as the load's pointer. 11556 if (Ptr != Base) 11557 return false; 11558 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC; 11559 return true; 11560 } 11561 11562 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results, 11563 SelectionDAG &DAG) { 11564 SDLoc DL(N); 11565 SDValue Op = N->getOperand(0); 11566 11567 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16) 11568 return; 11569 11570 Op = SDValue( 11571 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32, 11572 DAG.getUNDEF(MVT::i32), Op, 11573 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)), 11574 0); 11575 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op); 11576 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op)); 11577 } 11578 11579 static void ReplaceReductionResults(SDNode *N, 11580 SmallVectorImpl<SDValue> &Results, 11581 SelectionDAG &DAG, unsigned InterOp, 11582 unsigned AcrossOp) { 11583 EVT LoVT, HiVT; 11584 SDValue Lo, Hi; 11585 SDLoc dl(N); 11586 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0)); 11587 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0); 11588 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi); 11589 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal); 11590 Results.push_back(SplitVal); 11591 } 11592 11593 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) { 11594 SDLoc DL(N); 11595 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N); 11596 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, 11597 DAG.getNode(ISD::SRL, DL, MVT::i128, N, 11598 DAG.getConstant(64, DL, MVT::i64))); 11599 return std::make_pair(Lo, Hi); 11600 } 11601 11602 // Create an even/odd pair of X registers holding integer value V. 11603 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) { 11604 SDLoc dl(V.getNode()); 11605 SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64); 11606 SDValue VHi = DAG.getAnyExtOrTrunc( 11607 DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)), 11608 dl, MVT::i64); 11609 if (DAG.getDataLayout().isBigEndian()) 11610 std::swap (VLo, VHi); 11611 SDValue RegClass = 11612 DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32); 11613 SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32); 11614 SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32); 11615 const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 }; 11616 return SDValue( 11617 DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0); 11618 } 11619 11620 static void ReplaceCMP_SWAP_128Results(SDNode *N, 11621 SmallVectorImpl<SDValue> &Results, 11622 SelectionDAG &DAG, 11623 const AArch64Subtarget *Subtarget) { 11624 assert(N->getValueType(0) == MVT::i128 && 11625 "AtomicCmpSwap on types less than 128 should be legal"); 11626 11627 if (Subtarget->hasLSE()) { 11628 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type, 11629 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG. 11630 SDValue Ops[] = { 11631 createGPRPairNode(DAG, N->getOperand(2)), // Compare value 11632 createGPRPairNode(DAG, N->getOperand(3)), // Store value 11633 N->getOperand(1), // Ptr 11634 N->getOperand(0), // Chain in 11635 }; 11636 11637 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 11638 11639 unsigned Opcode; 11640 switch (MemOp->getOrdering()) { 11641 case AtomicOrdering::Monotonic: 11642 Opcode = AArch64::CASPX; 11643 break; 11644 case AtomicOrdering::Acquire: 11645 Opcode = AArch64::CASPAX; 11646 break; 11647 case AtomicOrdering::Release: 11648 Opcode = AArch64::CASPLX; 11649 break; 11650 case AtomicOrdering::AcquireRelease: 11651 case AtomicOrdering::SequentiallyConsistent: 11652 Opcode = AArch64::CASPALX; 11653 break; 11654 default: 11655 llvm_unreachable("Unexpected ordering!"); 11656 } 11657 11658 MachineSDNode *CmpSwap = DAG.getMachineNode( 11659 Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops); 11660 DAG.setNodeMemRefs(CmpSwap, {MemOp}); 11661 11662 unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64; 11663 if (DAG.getDataLayout().isBigEndian()) 11664 std::swap(SubReg1, SubReg2); 11665 Results.push_back(DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64, 11666 SDValue(CmpSwap, 0))); 11667 Results.push_back(DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64, 11668 SDValue(CmpSwap, 0))); 11669 Results.push_back(SDValue(CmpSwap, 1)); // Chain out 11670 return; 11671 } 11672 11673 auto Desired = splitInt128(N->getOperand(2), DAG); 11674 auto New = splitInt128(N->getOperand(3), DAG); 11675 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second, 11676 New.first, New.second, N->getOperand(0)}; 11677 SDNode *CmpSwap = DAG.getMachineNode( 11678 AArch64::CMP_SWAP_128, SDLoc(N), 11679 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops); 11680 11681 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 11682 DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp}); 11683 11684 Results.push_back(SDValue(CmpSwap, 0)); 11685 Results.push_back(SDValue(CmpSwap, 1)); 11686 Results.push_back(SDValue(CmpSwap, 3)); 11687 } 11688 11689 void AArch64TargetLowering::ReplaceNodeResults( 11690 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const { 11691 switch (N->getOpcode()) { 11692 default: 11693 llvm_unreachable("Don't know how to custom expand this"); 11694 case ISD::BITCAST: 11695 ReplaceBITCASTResults(N, Results, DAG); 11696 return; 11697 case ISD::VECREDUCE_ADD: 11698 case ISD::VECREDUCE_SMAX: 11699 case ISD::VECREDUCE_SMIN: 11700 case ISD::VECREDUCE_UMAX: 11701 case ISD::VECREDUCE_UMIN: 11702 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG)); 11703 return; 11704 11705 case AArch64ISD::SADDV: 11706 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV); 11707 return; 11708 case AArch64ISD::UADDV: 11709 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV); 11710 return; 11711 case AArch64ISD::SMINV: 11712 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV); 11713 return; 11714 case AArch64ISD::UMINV: 11715 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV); 11716 return; 11717 case AArch64ISD::SMAXV: 11718 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV); 11719 return; 11720 case AArch64ISD::UMAXV: 11721 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV); 11722 return; 11723 case ISD::FP_TO_UINT: 11724 case ISD::FP_TO_SINT: 11725 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion"); 11726 // Let normal code take care of it by not adding anything to Results. 11727 return; 11728 case ISD::ATOMIC_CMP_SWAP: 11729 ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget); 11730 return; 11731 } 11732 } 11733 11734 bool AArch64TargetLowering::useLoadStackGuardNode() const { 11735 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia()) 11736 return TargetLowering::useLoadStackGuardNode(); 11737 return true; 11738 } 11739 11740 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const { 11741 // Combine multiple FDIVs with the same divisor into multiple FMULs by the 11742 // reciprocal if there are three or more FDIVs. 11743 return 3; 11744 } 11745 11746 TargetLoweringBase::LegalizeTypeAction 11747 AArch64TargetLowering::getPreferredVectorAction(MVT VT) const { 11748 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8, 11749 // v4i16, v2i32 instead of to promote. 11750 if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 || 11751 VT == MVT::v1f32) 11752 return TypeWidenVector; 11753 11754 return TargetLoweringBase::getPreferredVectorAction(VT); 11755 } 11756 11757 // Loads and stores less than 128-bits are already atomic; ones above that 11758 // are doomed anyway, so defer to the default libcall and blame the OS when 11759 // things go wrong. 11760 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const { 11761 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits(); 11762 return Size == 128; 11763 } 11764 11765 // Loads and stores less than 128-bits are already atomic; ones above that 11766 // are doomed anyway, so defer to the default libcall and blame the OS when 11767 // things go wrong. 11768 TargetLowering::AtomicExpansionKind 11769 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const { 11770 unsigned Size = LI->getType()->getPrimitiveSizeInBits(); 11771 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None; 11772 } 11773 11774 // For the real atomic operations, we have ldxr/stxr up to 128 bits, 11775 TargetLowering::AtomicExpansionKind 11776 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11777 if (AI->isFloatingPointOperation()) 11778 return AtomicExpansionKind::CmpXChg; 11779 11780 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11781 if (Size > 128) return AtomicExpansionKind::None; 11782 // Nand not supported in LSE. 11783 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC; 11784 // Leave 128 bits to LLSC. 11785 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC; 11786 } 11787 11788 TargetLowering::AtomicExpansionKind 11789 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR( 11790 AtomicCmpXchgInst *AI) const { 11791 // If subtarget has LSE, leave cmpxchg intact for codegen. 11792 if (Subtarget->hasLSE()) 11793 return AtomicExpansionKind::None; 11794 // At -O0, fast-regalloc cannot cope with the live vregs necessary to 11795 // implement cmpxchg without spilling. If the address being exchanged is also 11796 // on the stack and close enough to the spill slot, this can lead to a 11797 // situation where the monitor always gets cleared and the atomic operation 11798 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead. 11799 if (getTargetMachine().getOptLevel() == 0) 11800 return AtomicExpansionKind::None; 11801 return AtomicExpansionKind::LLSC; 11802 } 11803 11804 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr, 11805 AtomicOrdering Ord) const { 11806 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11807 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType(); 11808 bool IsAcquire = isAcquireOrStronger(Ord); 11809 11810 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd 11811 // intrinsic must return {i64, i64} and we have to recombine them into a 11812 // single i128 here. 11813 if (ValTy->getPrimitiveSizeInBits() == 128) { 11814 Intrinsic::ID Int = 11815 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp; 11816 Function *Ldxr = Intrinsic::getDeclaration(M, Int); 11817 11818 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 11819 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi"); 11820 11821 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo"); 11822 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi"); 11823 Lo = Builder.CreateZExt(Lo, ValTy, "lo64"); 11824 Hi = Builder.CreateZExt(Hi, ValTy, "hi64"); 11825 return Builder.CreateOr( 11826 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64"); 11827 } 11828 11829 Type *Tys[] = { Addr->getType() }; 11830 Intrinsic::ID Int = 11831 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr; 11832 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys); 11833 11834 Type *EltTy = cast<PointerType>(Addr->getType())->getElementType(); 11835 11836 const DataLayout &DL = M->getDataLayout(); 11837 IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy)); 11838 Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy); 11839 11840 return Builder.CreateBitCast(Trunc, EltTy); 11841 } 11842 11843 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance( 11844 IRBuilder<> &Builder) const { 11845 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11846 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex)); 11847 } 11848 11849 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder, 11850 Value *Val, Value *Addr, 11851 AtomicOrdering Ord) const { 11852 Module *M = Builder.GetInsertBlock()->getParent()->getParent(); 11853 bool IsRelease = isReleaseOrStronger(Ord); 11854 11855 // Since the intrinsics must have legal type, the i128 intrinsics take two 11856 // parameters: "i64, i64". We must marshal Val into the appropriate form 11857 // before the call. 11858 if (Val->getType()->getPrimitiveSizeInBits() == 128) { 11859 Intrinsic::ID Int = 11860 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp; 11861 Function *Stxr = Intrinsic::getDeclaration(M, Int); 11862 Type *Int64Ty = Type::getInt64Ty(M->getContext()); 11863 11864 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo"); 11865 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi"); 11866 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext())); 11867 return Builder.CreateCall(Stxr, {Lo, Hi, Addr}); 11868 } 11869 11870 Intrinsic::ID Int = 11871 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr; 11872 Type *Tys[] = { Addr->getType() }; 11873 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys); 11874 11875 const DataLayout &DL = M->getDataLayout(); 11876 IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType())); 11877 Val = Builder.CreateBitCast(Val, IntValTy); 11878 11879 return Builder.CreateCall(Stxr, 11880 {Builder.CreateZExtOrBitCast( 11881 Val, Stxr->getFunctionType()->getParamType(0)), 11882 Addr}); 11883 } 11884 11885 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters( 11886 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const { 11887 return Ty->isArrayTy(); 11888 } 11889 11890 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &, 11891 EVT) const { 11892 return false; 11893 } 11894 11895 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) { 11896 Module *M = IRB.GetInsertBlock()->getParent()->getParent(); 11897 Function *ThreadPointerFunc = 11898 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer); 11899 return IRB.CreatePointerCast( 11900 IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc), 11901 Offset), 11902 IRB.getInt8PtrTy()->getPointerTo(0)); 11903 } 11904 11905 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const { 11906 // Android provides a fixed TLS slot for the stack cookie. See the definition 11907 // of TLS_SLOT_STACK_GUARD in 11908 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 11909 if (Subtarget->isTargetAndroid()) 11910 return UseTlsOffset(IRB, 0x28); 11911 11912 // Fuchsia is similar. 11913 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value. 11914 if (Subtarget->isTargetFuchsia()) 11915 return UseTlsOffset(IRB, -0x10); 11916 11917 return TargetLowering::getIRStackGuard(IRB); 11918 } 11919 11920 void AArch64TargetLowering::insertSSPDeclarations(Module &M) const { 11921 // MSVC CRT provides functionalities for stack protection. 11922 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) { 11923 // MSVC CRT has a global variable holding security cookie. 11924 M.getOrInsertGlobal("__security_cookie", 11925 Type::getInt8PtrTy(M.getContext())); 11926 11927 // MSVC CRT has a function to validate security cookie. 11928 FunctionCallee SecurityCheckCookie = M.getOrInsertFunction( 11929 "__security_check_cookie", Type::getVoidTy(M.getContext()), 11930 Type::getInt8PtrTy(M.getContext())); 11931 if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) { 11932 F->setCallingConv(CallingConv::Win64); 11933 F->addAttribute(1, Attribute::AttrKind::InReg); 11934 } 11935 return; 11936 } 11937 TargetLowering::insertSSPDeclarations(M); 11938 } 11939 11940 Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const { 11941 // MSVC CRT has a global variable holding security cookie. 11942 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 11943 return M.getGlobalVariable("__security_cookie"); 11944 return TargetLowering::getSDagStackGuard(M); 11945 } 11946 11947 Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const { 11948 // MSVC CRT has a function to validate security cookie. 11949 if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) 11950 return M.getFunction("__security_check_cookie"); 11951 return TargetLowering::getSSPStackGuardCheck(M); 11952 } 11953 11954 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const { 11955 // Android provides a fixed TLS slot for the SafeStack pointer. See the 11956 // definition of TLS_SLOT_SAFESTACK in 11957 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h 11958 if (Subtarget->isTargetAndroid()) 11959 return UseTlsOffset(IRB, 0x48); 11960 11961 // Fuchsia is similar. 11962 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value. 11963 if (Subtarget->isTargetFuchsia()) 11964 return UseTlsOffset(IRB, -0x8); 11965 11966 return TargetLowering::getSafeStackPointerLocation(IRB); 11967 } 11968 11969 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial( 11970 const Instruction &AndI) const { 11971 // Only sink 'and' mask to cmp use block if it is masking a single bit, since 11972 // this is likely to be fold the and/cmp/br into a single tbz instruction. It 11973 // may be beneficial to sink in other cases, but we would have to check that 11974 // the cmp would not get folded into the br to form a cbz for these to be 11975 // beneficial. 11976 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1)); 11977 if (!Mask) 11978 return false; 11979 return Mask->getValue().isPowerOf2(); 11980 } 11981 11982 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const { 11983 // Update IsSplitCSR in AArch64unctionInfo. 11984 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>(); 11985 AFI->setIsSplitCSR(true); 11986 } 11987 11988 void AArch64TargetLowering::insertCopiesSplitCSR( 11989 MachineBasicBlock *Entry, 11990 const SmallVectorImpl<MachineBasicBlock *> &Exits) const { 11991 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo(); 11992 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent()); 11993 if (!IStart) 11994 return; 11995 11996 const TargetInstrInfo *TII = Subtarget->getInstrInfo(); 11997 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo(); 11998 MachineBasicBlock::iterator MBBI = Entry->begin(); 11999 for (const MCPhysReg *I = IStart; *I; ++I) { 12000 const TargetRegisterClass *RC = nullptr; 12001 if (AArch64::GPR64RegClass.contains(*I)) 12002 RC = &AArch64::GPR64RegClass; 12003 else if (AArch64::FPR64RegClass.contains(*I)) 12004 RC = &AArch64::FPR64RegClass; 12005 else 12006 llvm_unreachable("Unexpected register class in CSRsViaCopy!"); 12007 12008 unsigned NewVR = MRI->createVirtualRegister(RC); 12009 // Create copy from CSR to a virtual register. 12010 // FIXME: this currently does not emit CFI pseudo-instructions, it works 12011 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be 12012 // nounwind. If we want to generalize this later, we may need to emit 12013 // CFI pseudo-instructions. 12014 assert(Entry->getParent()->getFunction().hasFnAttribute( 12015 Attribute::NoUnwind) && 12016 "Function should be nounwind in insertCopiesSplitCSR!"); 12017 Entry->addLiveIn(*I); 12018 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR) 12019 .addReg(*I); 12020 12021 // Insert the copy-back instructions right before the terminator. 12022 for (auto *Exit : Exits) 12023 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(), 12024 TII->get(TargetOpcode::COPY), *I) 12025 .addReg(NewVR); 12026 } 12027 } 12028 12029 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const { 12030 // Integer division on AArch64 is expensive. However, when aggressively 12031 // optimizing for code size, we prefer to use a div instruction, as it is 12032 // usually smaller than the alternative sequence. 12033 // The exception to this is vector division. Since AArch64 doesn't have vector 12034 // integer division, leaving the division as-is is a loss even in terms of 12035 // size, because it will have to be scalarized, while the alternative code 12036 // sequence can be performed in vector form. 12037 bool OptSize = 12038 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize); 12039 return OptSize && !VT.isVector(); 12040 } 12041 12042 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const { 12043 return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint(); 12044 } 12045 12046 unsigned 12047 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const { 12048 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows()) 12049 return getPointerTy(DL).getSizeInBits(); 12050 12051 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32; 12052 } 12053 12054 void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const { 12055 MF.getFrameInfo().computeMaxCallFrameSize(MF); 12056 TargetLoweringBase::finalizeLowering(MF); 12057 } 12058 12059 // Unlike X86, we let frame lowering assign offsets to all catch objects. 12060 bool AArch64TargetLowering::needsFixedCatchObjects() const { 12061 return false; 12062 } 12063