1 //===-- AArch64TargetTransformInfo.cpp - AArch64 specific TTI -------------===// 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 #include "AArch64TargetTransformInfo.h" 10 #include "AArch64ExpandImm.h" 11 #include "MCTargetDesc/AArch64AddressingModes.h" 12 #include "llvm/Analysis/LoopInfo.h" 13 #include "llvm/Analysis/TargetTransformInfo.h" 14 #include "llvm/CodeGen/BasicTTIImpl.h" 15 #include "llvm/CodeGen/CostTable.h" 16 #include "llvm/CodeGen/TargetLowering.h" 17 #include "llvm/IR/IntrinsicInst.h" 18 #include "llvm/IR/IntrinsicsAArch64.h" 19 #include "llvm/IR/PatternMatch.h" 20 #include "llvm/Support/Debug.h" 21 #include <algorithm> 22 using namespace llvm; 23 using namespace llvm::PatternMatch; 24 25 #define DEBUG_TYPE "aarch64tti" 26 27 static cl::opt<bool> EnableFalkorHWPFUnrollFix("enable-falkor-hwpf-unroll-fix", 28 cl::init(true), cl::Hidden); 29 30 bool AArch64TTIImpl::areInlineCompatible(const Function *Caller, 31 const Function *Callee) const { 32 const TargetMachine &TM = getTLI()->getTargetMachine(); 33 34 const FeatureBitset &CallerBits = 35 TM.getSubtargetImpl(*Caller)->getFeatureBits(); 36 const FeatureBitset &CalleeBits = 37 TM.getSubtargetImpl(*Callee)->getFeatureBits(); 38 39 // Inline a callee if its target-features are a subset of the callers 40 // target-features. 41 return (CallerBits & CalleeBits) == CalleeBits; 42 } 43 44 /// Calculate the cost of materializing a 64-bit value. This helper 45 /// method might only calculate a fraction of a larger immediate. Therefore it 46 /// is valid to return a cost of ZERO. 47 int AArch64TTIImpl::getIntImmCost(int64_t Val) { 48 // Check if the immediate can be encoded within an instruction. 49 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, 64)) 50 return 0; 51 52 if (Val < 0) 53 Val = ~Val; 54 55 // Calculate how many moves we will need to materialize this constant. 56 SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn; 57 AArch64_IMM::expandMOVImm(Val, 64, Insn); 58 return Insn.size(); 59 } 60 61 /// Calculate the cost of materializing the given constant. 62 int AArch64TTIImpl::getIntImmCost(const APInt &Imm, Type *Ty, 63 TTI::TargetCostKind CostKind) { 64 assert(Ty->isIntegerTy()); 65 66 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 67 if (BitSize == 0) 68 return ~0U; 69 70 // Sign-extend all constants to a multiple of 64-bit. 71 APInt ImmVal = Imm; 72 if (BitSize & 0x3f) 73 ImmVal = Imm.sext((BitSize + 63) & ~0x3fU); 74 75 // Split the constant into 64-bit chunks and calculate the cost for each 76 // chunk. 77 int Cost = 0; 78 for (unsigned ShiftVal = 0; ShiftVal < BitSize; ShiftVal += 64) { 79 APInt Tmp = ImmVal.ashr(ShiftVal).sextOrTrunc(64); 80 int64_t Val = Tmp.getSExtValue(); 81 Cost += getIntImmCost(Val); 82 } 83 // We need at least one instruction to materialze the constant. 84 return std::max(1, Cost); 85 } 86 87 int AArch64TTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx, 88 const APInt &Imm, Type *Ty, 89 TTI::TargetCostKind CostKind, 90 Instruction *Inst) { 91 assert(Ty->isIntegerTy()); 92 93 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 94 // There is no cost model for constants with a bit size of 0. Return TCC_Free 95 // here, so that constant hoisting will ignore this constant. 96 if (BitSize == 0) 97 return TTI::TCC_Free; 98 99 unsigned ImmIdx = ~0U; 100 switch (Opcode) { 101 default: 102 return TTI::TCC_Free; 103 case Instruction::GetElementPtr: 104 // Always hoist the base address of a GetElementPtr. 105 if (Idx == 0) 106 return 2 * TTI::TCC_Basic; 107 return TTI::TCC_Free; 108 case Instruction::Store: 109 ImmIdx = 0; 110 break; 111 case Instruction::Add: 112 case Instruction::Sub: 113 case Instruction::Mul: 114 case Instruction::UDiv: 115 case Instruction::SDiv: 116 case Instruction::URem: 117 case Instruction::SRem: 118 case Instruction::And: 119 case Instruction::Or: 120 case Instruction::Xor: 121 case Instruction::ICmp: 122 ImmIdx = 1; 123 break; 124 // Always return TCC_Free for the shift value of a shift instruction. 125 case Instruction::Shl: 126 case Instruction::LShr: 127 case Instruction::AShr: 128 if (Idx == 1) 129 return TTI::TCC_Free; 130 break; 131 case Instruction::Trunc: 132 case Instruction::ZExt: 133 case Instruction::SExt: 134 case Instruction::IntToPtr: 135 case Instruction::PtrToInt: 136 case Instruction::BitCast: 137 case Instruction::PHI: 138 case Instruction::Call: 139 case Instruction::Select: 140 case Instruction::Ret: 141 case Instruction::Load: 142 break; 143 } 144 145 if (Idx == ImmIdx) { 146 int NumConstants = (BitSize + 63) / 64; 147 int Cost = AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind); 148 return (Cost <= NumConstants * TTI::TCC_Basic) 149 ? static_cast<int>(TTI::TCC_Free) 150 : Cost; 151 } 152 return AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind); 153 } 154 155 int AArch64TTIImpl::getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx, 156 const APInt &Imm, Type *Ty, 157 TTI::TargetCostKind CostKind) { 158 assert(Ty->isIntegerTy()); 159 160 unsigned BitSize = Ty->getPrimitiveSizeInBits(); 161 // There is no cost model for constants with a bit size of 0. Return TCC_Free 162 // here, so that constant hoisting will ignore this constant. 163 if (BitSize == 0) 164 return TTI::TCC_Free; 165 166 // Most (all?) AArch64 intrinsics do not support folding immediates into the 167 // selected instruction, so we compute the materialization cost for the 168 // immediate directly. 169 if (IID >= Intrinsic::aarch64_addg && IID <= Intrinsic::aarch64_udiv) 170 return AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind); 171 172 switch (IID) { 173 default: 174 return TTI::TCC_Free; 175 case Intrinsic::sadd_with_overflow: 176 case Intrinsic::uadd_with_overflow: 177 case Intrinsic::ssub_with_overflow: 178 case Intrinsic::usub_with_overflow: 179 case Intrinsic::smul_with_overflow: 180 case Intrinsic::umul_with_overflow: 181 if (Idx == 1) { 182 int NumConstants = (BitSize + 63) / 64; 183 int Cost = AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind); 184 return (Cost <= NumConstants * TTI::TCC_Basic) 185 ? static_cast<int>(TTI::TCC_Free) 186 : Cost; 187 } 188 break; 189 case Intrinsic::experimental_stackmap: 190 if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue()))) 191 return TTI::TCC_Free; 192 break; 193 case Intrinsic::experimental_patchpoint_void: 194 case Intrinsic::experimental_patchpoint_i64: 195 if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue()))) 196 return TTI::TCC_Free; 197 break; 198 case Intrinsic::experimental_gc_statepoint: 199 if ((Idx < 5) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue()))) 200 return TTI::TCC_Free; 201 break; 202 } 203 return AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind); 204 } 205 206 TargetTransformInfo::PopcntSupportKind 207 AArch64TTIImpl::getPopcntSupport(unsigned TyWidth) { 208 assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2"); 209 if (TyWidth == 32 || TyWidth == 64) 210 return TTI::PSK_FastHardware; 211 // TODO: AArch64TargetLowering::LowerCTPOP() supports 128bit popcount. 212 return TTI::PSK_Software; 213 } 214 215 unsigned 216 AArch64TTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, 217 TTI::TargetCostKind CostKind) { 218 auto *RetTy = ICA.getReturnType(); 219 switch (ICA.getID()) { 220 case Intrinsic::umin: 221 case Intrinsic::umax: { 222 auto LT = TLI->getTypeLegalizationCost(DL, RetTy); 223 // umin(x,y) -> sub(x,usubsat(x,y)) 224 // umax(x,y) -> add(x,usubsat(y,x)) 225 if (LT.second == MVT::v2i64) 226 return LT.first * 2; 227 LLVM_FALLTHROUGH; 228 } 229 case Intrinsic::smin: 230 case Intrinsic::smax: { 231 static const auto ValidMinMaxTys = {MVT::v8i8, MVT::v16i8, MVT::v4i16, 232 MVT::v8i16, MVT::v2i32, MVT::v4i32}; 233 auto LT = TLI->getTypeLegalizationCost(DL, RetTy); 234 if (any_of(ValidMinMaxTys, [<](MVT M) { return M == LT.second; })) 235 return LT.first; 236 break; 237 } 238 case Intrinsic::sadd_sat: 239 case Intrinsic::ssub_sat: 240 case Intrinsic::uadd_sat: 241 case Intrinsic::usub_sat: { 242 static const auto ValidSatTys = {MVT::v8i8, MVT::v16i8, MVT::v4i16, 243 MVT::v8i16, MVT::v2i32, MVT::v4i32, 244 MVT::v2i64}; 245 auto LT = TLI->getTypeLegalizationCost(DL, RetTy); 246 // This is a base cost of 1 for the vadd, plus 3 extract shifts if we 247 // need to extend the type, as it uses shr(qadd(shl, shl)). 248 unsigned Instrs = 249 LT.second.getScalarSizeInBits() == RetTy->getScalarSizeInBits() ? 1 : 4; 250 if (any_of(ValidSatTys, [<](MVT M) { return M == LT.second; })) 251 return LT.first * Instrs; 252 break; 253 } 254 case Intrinsic::abs: { 255 static const auto ValidAbsTys = {MVT::v8i8, MVT::v16i8, MVT::v4i16, 256 MVT::v8i16, MVT::v2i32, MVT::v4i32, 257 MVT::v2i64}; 258 auto LT = TLI->getTypeLegalizationCost(DL, RetTy); 259 if (any_of(ValidAbsTys, [<](MVT M) { return M == LT.second; })) 260 return LT.first; 261 break; 262 } 263 default: 264 break; 265 } 266 return BaseT::getIntrinsicInstrCost(ICA, CostKind); 267 } 268 269 bool AArch64TTIImpl::isWideningInstruction(Type *DstTy, unsigned Opcode, 270 ArrayRef<const Value *> Args) { 271 272 // A helper that returns a vector type from the given type. The number of 273 // elements in type Ty determine the vector width. 274 auto toVectorTy = [&](Type *ArgTy) { 275 return VectorType::get(ArgTy->getScalarType(), 276 cast<VectorType>(DstTy)->getElementCount()); 277 }; 278 279 // Exit early if DstTy is not a vector type whose elements are at least 280 // 16-bits wide. 281 if (!DstTy->isVectorTy() || DstTy->getScalarSizeInBits() < 16) 282 return false; 283 284 // Determine if the operation has a widening variant. We consider both the 285 // "long" (e.g., usubl) and "wide" (e.g., usubw) versions of the 286 // instructions. 287 // 288 // TODO: Add additional widening operations (e.g., mul, shl, etc.) once we 289 // verify that their extending operands are eliminated during code 290 // generation. 291 switch (Opcode) { 292 case Instruction::Add: // UADDL(2), SADDL(2), UADDW(2), SADDW(2). 293 case Instruction::Sub: // USUBL(2), SSUBL(2), USUBW(2), SSUBW(2). 294 break; 295 default: 296 return false; 297 } 298 299 // To be a widening instruction (either the "wide" or "long" versions), the 300 // second operand must be a sign- or zero extend having a single user. We 301 // only consider extends having a single user because they may otherwise not 302 // be eliminated. 303 if (Args.size() != 2 || 304 (!isa<SExtInst>(Args[1]) && !isa<ZExtInst>(Args[1])) || 305 !Args[1]->hasOneUse()) 306 return false; 307 auto *Extend = cast<CastInst>(Args[1]); 308 309 // Legalize the destination type and ensure it can be used in a widening 310 // operation. 311 auto DstTyL = TLI->getTypeLegalizationCost(DL, DstTy); 312 unsigned DstElTySize = DstTyL.second.getScalarSizeInBits(); 313 if (!DstTyL.second.isVector() || DstElTySize != DstTy->getScalarSizeInBits()) 314 return false; 315 316 // Legalize the source type and ensure it can be used in a widening 317 // operation. 318 auto *SrcTy = toVectorTy(Extend->getSrcTy()); 319 auto SrcTyL = TLI->getTypeLegalizationCost(DL, SrcTy); 320 unsigned SrcElTySize = SrcTyL.second.getScalarSizeInBits(); 321 if (!SrcTyL.second.isVector() || SrcElTySize != SrcTy->getScalarSizeInBits()) 322 return false; 323 324 // Get the total number of vector elements in the legalized types. 325 unsigned NumDstEls = DstTyL.first * DstTyL.second.getVectorMinNumElements(); 326 unsigned NumSrcEls = SrcTyL.first * SrcTyL.second.getVectorMinNumElements(); 327 328 // Return true if the legalized types have the same number of vector elements 329 // and the destination element type size is twice that of the source type. 330 return NumDstEls == NumSrcEls && 2 * SrcElTySize == DstElTySize; 331 } 332 333 int AArch64TTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, 334 TTI::CastContextHint CCH, 335 TTI::TargetCostKind CostKind, 336 const Instruction *I) { 337 int ISD = TLI->InstructionOpcodeToISD(Opcode); 338 assert(ISD && "Invalid opcode"); 339 340 // If the cast is observable, and it is used by a widening instruction (e.g., 341 // uaddl, saddw, etc.), it may be free. 342 if (I && I->hasOneUse()) { 343 auto *SingleUser = cast<Instruction>(*I->user_begin()); 344 SmallVector<const Value *, 4> Operands(SingleUser->operand_values()); 345 if (isWideningInstruction(Dst, SingleUser->getOpcode(), Operands)) { 346 // If the cast is the second operand, it is free. We will generate either 347 // a "wide" or "long" version of the widening instruction. 348 if (I == SingleUser->getOperand(1)) 349 return 0; 350 // If the cast is not the second operand, it will be free if it looks the 351 // same as the second operand. In this case, we will generate a "long" 352 // version of the widening instruction. 353 if (auto *Cast = dyn_cast<CastInst>(SingleUser->getOperand(1))) 354 if (I->getOpcode() == unsigned(Cast->getOpcode()) && 355 cast<CastInst>(I)->getSrcTy() == Cast->getSrcTy()) 356 return 0; 357 } 358 } 359 360 // TODO: Allow non-throughput costs that aren't binary. 361 auto AdjustCost = [&CostKind](int Cost) { 362 if (CostKind != TTI::TCK_RecipThroughput) 363 return Cost == 0 ? 0 : 1; 364 return Cost; 365 }; 366 367 EVT SrcTy = TLI->getValueType(DL, Src); 368 EVT DstTy = TLI->getValueType(DL, Dst); 369 370 if (!SrcTy.isSimple() || !DstTy.isSimple()) 371 return AdjustCost( 372 BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I)); 373 374 static const TypeConversionCostTblEntry 375 ConversionTbl[] = { 376 { ISD::TRUNCATE, MVT::v4i16, MVT::v4i32, 1 }, 377 { ISD::TRUNCATE, MVT::v4i32, MVT::v4i64, 0 }, 378 { ISD::TRUNCATE, MVT::v8i8, MVT::v8i32, 3 }, 379 { ISD::TRUNCATE, MVT::v16i8, MVT::v16i32, 6 }, 380 381 // The number of shll instructions for the extension. 382 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16, 3 }, 383 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16, 3 }, 384 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i32, 2 }, 385 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i32, 2 }, 386 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i8, 3 }, 387 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i8, 3 }, 388 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 2 }, 389 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 2 }, 390 { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i8, 7 }, 391 { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i8, 7 }, 392 { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i16, 6 }, 393 { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i16, 6 }, 394 { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 2 }, 395 { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 2 }, 396 { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 6 }, 397 { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 6 }, 398 399 // LowerVectorINT_TO_FP: 400 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 }, 401 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 }, 402 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i64, 1 }, 403 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 }, 404 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 }, 405 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i64, 1 }, 406 407 // Complex: to v2f32 408 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i8, 3 }, 409 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i16, 3 }, 410 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i64, 2 }, 411 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i8, 3 }, 412 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i16, 3 }, 413 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i64, 2 }, 414 415 // Complex: to v4f32 416 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i8, 4 }, 417 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 }, 418 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i8, 3 }, 419 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 }, 420 421 // Complex: to v8f32 422 { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i8, 10 }, 423 { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 }, 424 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i8, 10 }, 425 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 }, 426 427 // Complex: to v16f32 428 { ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i8, 21 }, 429 { ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i8, 21 }, 430 431 // Complex: to v2f64 432 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i8, 4 }, 433 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i16, 4 }, 434 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 }, 435 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i8, 4 }, 436 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i16, 4 }, 437 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 }, 438 439 440 // LowerVectorFP_TO_INT 441 { ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f32, 1 }, 442 { ISD::FP_TO_SINT, MVT::v4i32, MVT::v4f32, 1 }, 443 { ISD::FP_TO_SINT, MVT::v2i64, MVT::v2f64, 1 }, 444 { ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f32, 1 }, 445 { ISD::FP_TO_UINT, MVT::v4i32, MVT::v4f32, 1 }, 446 { ISD::FP_TO_UINT, MVT::v2i64, MVT::v2f64, 1 }, 447 448 // Complex, from v2f32: legal type is v2i32 (no cost) or v2i64 (1 ext). 449 { ISD::FP_TO_SINT, MVT::v2i64, MVT::v2f32, 2 }, 450 { ISD::FP_TO_SINT, MVT::v2i16, MVT::v2f32, 1 }, 451 { ISD::FP_TO_SINT, MVT::v2i8, MVT::v2f32, 1 }, 452 { ISD::FP_TO_UINT, MVT::v2i64, MVT::v2f32, 2 }, 453 { ISD::FP_TO_UINT, MVT::v2i16, MVT::v2f32, 1 }, 454 { ISD::FP_TO_UINT, MVT::v2i8, MVT::v2f32, 1 }, 455 456 // Complex, from v4f32: legal type is v4i16, 1 narrowing => ~2 457 { ISD::FP_TO_SINT, MVT::v4i16, MVT::v4f32, 2 }, 458 { ISD::FP_TO_SINT, MVT::v4i8, MVT::v4f32, 2 }, 459 { ISD::FP_TO_UINT, MVT::v4i16, MVT::v4f32, 2 }, 460 { ISD::FP_TO_UINT, MVT::v4i8, MVT::v4f32, 2 }, 461 462 // Complex, from v2f64: legal type is v2i32, 1 narrowing => ~2. 463 { ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f64, 2 }, 464 { ISD::FP_TO_SINT, MVT::v2i16, MVT::v2f64, 2 }, 465 { ISD::FP_TO_SINT, MVT::v2i8, MVT::v2f64, 2 }, 466 { ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f64, 2 }, 467 { ISD::FP_TO_UINT, MVT::v2i16, MVT::v2f64, 2 }, 468 { ISD::FP_TO_UINT, MVT::v2i8, MVT::v2f64, 2 }, 469 }; 470 471 if (const auto *Entry = ConvertCostTableLookup(ConversionTbl, ISD, 472 DstTy.getSimpleVT(), 473 SrcTy.getSimpleVT())) 474 return AdjustCost(Entry->Cost); 475 476 return AdjustCost( 477 BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I)); 478 } 479 480 int AArch64TTIImpl::getExtractWithExtendCost(unsigned Opcode, Type *Dst, 481 VectorType *VecTy, 482 unsigned Index) { 483 484 // Make sure we were given a valid extend opcode. 485 assert((Opcode == Instruction::SExt || Opcode == Instruction::ZExt) && 486 "Invalid opcode"); 487 488 // We are extending an element we extract from a vector, so the source type 489 // of the extend is the element type of the vector. 490 auto *Src = VecTy->getElementType(); 491 492 // Sign- and zero-extends are for integer types only. 493 assert(isa<IntegerType>(Dst) && isa<IntegerType>(Src) && "Invalid type"); 494 495 // Get the cost for the extract. We compute the cost (if any) for the extend 496 // below. 497 auto Cost = getVectorInstrCost(Instruction::ExtractElement, VecTy, Index); 498 499 // Legalize the types. 500 auto VecLT = TLI->getTypeLegalizationCost(DL, VecTy); 501 auto DstVT = TLI->getValueType(DL, Dst); 502 auto SrcVT = TLI->getValueType(DL, Src); 503 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput; 504 505 // If the resulting type is still a vector and the destination type is legal, 506 // we may get the extension for free. If not, get the default cost for the 507 // extend. 508 if (!VecLT.second.isVector() || !TLI->isTypeLegal(DstVT)) 509 return Cost + getCastInstrCost(Opcode, Dst, Src, TTI::CastContextHint::None, 510 CostKind); 511 512 // The destination type should be larger than the element type. If not, get 513 // the default cost for the extend. 514 if (DstVT.getFixedSizeInBits() < SrcVT.getFixedSizeInBits()) 515 return Cost + getCastInstrCost(Opcode, Dst, Src, TTI::CastContextHint::None, 516 CostKind); 517 518 switch (Opcode) { 519 default: 520 llvm_unreachable("Opcode should be either SExt or ZExt"); 521 522 // For sign-extends, we only need a smov, which performs the extension 523 // automatically. 524 case Instruction::SExt: 525 return Cost; 526 527 // For zero-extends, the extend is performed automatically by a umov unless 528 // the destination type is i64 and the element type is i8 or i16. 529 case Instruction::ZExt: 530 if (DstVT.getSizeInBits() != 64u || SrcVT.getSizeInBits() == 32u) 531 return Cost; 532 } 533 534 // If we are unable to perform the extend for free, get the default cost. 535 return Cost + getCastInstrCost(Opcode, Dst, Src, TTI::CastContextHint::None, 536 CostKind); 537 } 538 539 unsigned AArch64TTIImpl::getCFInstrCost(unsigned Opcode, 540 TTI::TargetCostKind CostKind) { 541 if (CostKind != TTI::TCK_RecipThroughput) 542 return Opcode == Instruction::PHI ? 0 : 1; 543 assert(CostKind == TTI::TCK_RecipThroughput && "unexpected CostKind"); 544 // Branches are assumed to be predicted. 545 return 0; 546 } 547 548 int AArch64TTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val, 549 unsigned Index) { 550 assert(Val->isVectorTy() && "This must be a vector type"); 551 552 if (Index != -1U) { 553 // Legalize the type. 554 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Val); 555 556 // This type is legalized to a scalar type. 557 if (!LT.second.isVector()) 558 return 0; 559 560 // The type may be split. Normalize the index to the new type. 561 unsigned Width = LT.second.getVectorNumElements(); 562 Index = Index % Width; 563 564 // The element at index zero is already inside the vector. 565 if (Index == 0) 566 return 0; 567 } 568 569 // All other insert/extracts cost this much. 570 return ST->getVectorInsertExtractBaseCost(); 571 } 572 573 int AArch64TTIImpl::getArithmeticInstrCost( 574 unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, 575 TTI::OperandValueKind Opd1Info, 576 TTI::OperandValueKind Opd2Info, TTI::OperandValueProperties Opd1PropInfo, 577 TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args, 578 const Instruction *CxtI) { 579 // TODO: Handle more cost kinds. 580 if (CostKind != TTI::TCK_RecipThroughput) 581 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info, 582 Opd2Info, Opd1PropInfo, 583 Opd2PropInfo, Args, CxtI); 584 585 // Legalize the type. 586 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 587 588 // If the instruction is a widening instruction (e.g., uaddl, saddw, etc.), 589 // add in the widening overhead specified by the sub-target. Since the 590 // extends feeding widening instructions are performed automatically, they 591 // aren't present in the generated code and have a zero cost. By adding a 592 // widening overhead here, we attach the total cost of the combined operation 593 // to the widening instruction. 594 int Cost = 0; 595 if (isWideningInstruction(Ty, Opcode, Args)) 596 Cost += ST->getWideningBaseCost(); 597 598 int ISD = TLI->InstructionOpcodeToISD(Opcode); 599 600 switch (ISD) { 601 default: 602 return Cost + BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info, 603 Opd2Info, 604 Opd1PropInfo, Opd2PropInfo); 605 case ISD::SDIV: 606 if (Opd2Info == TargetTransformInfo::OK_UniformConstantValue && 607 Opd2PropInfo == TargetTransformInfo::OP_PowerOf2) { 608 // On AArch64, scalar signed division by constants power-of-two are 609 // normally expanded to the sequence ADD + CMP + SELECT + SRA. 610 // The OperandValue properties many not be same as that of previous 611 // operation; conservatively assume OP_None. 612 Cost += getArithmeticInstrCost(Instruction::Add, Ty, CostKind, 613 Opd1Info, Opd2Info, 614 TargetTransformInfo::OP_None, 615 TargetTransformInfo::OP_None); 616 Cost += getArithmeticInstrCost(Instruction::Sub, Ty, CostKind, 617 Opd1Info, Opd2Info, 618 TargetTransformInfo::OP_None, 619 TargetTransformInfo::OP_None); 620 Cost += getArithmeticInstrCost(Instruction::Select, Ty, CostKind, 621 Opd1Info, Opd2Info, 622 TargetTransformInfo::OP_None, 623 TargetTransformInfo::OP_None); 624 Cost += getArithmeticInstrCost(Instruction::AShr, Ty, CostKind, 625 Opd1Info, Opd2Info, 626 TargetTransformInfo::OP_None, 627 TargetTransformInfo::OP_None); 628 return Cost; 629 } 630 LLVM_FALLTHROUGH; 631 case ISD::UDIV: 632 if (Opd2Info == TargetTransformInfo::OK_UniformConstantValue) { 633 auto VT = TLI->getValueType(DL, Ty); 634 if (TLI->isOperationLegalOrCustom(ISD::MULHU, VT)) { 635 // Vector signed division by constant are expanded to the 636 // sequence MULHS + ADD/SUB + SRA + SRL + ADD, and unsigned division 637 // to MULHS + SUB + SRL + ADD + SRL. 638 int MulCost = getArithmeticInstrCost(Instruction::Mul, Ty, CostKind, 639 Opd1Info, Opd2Info, 640 TargetTransformInfo::OP_None, 641 TargetTransformInfo::OP_None); 642 int AddCost = getArithmeticInstrCost(Instruction::Add, Ty, CostKind, 643 Opd1Info, Opd2Info, 644 TargetTransformInfo::OP_None, 645 TargetTransformInfo::OP_None); 646 int ShrCost = getArithmeticInstrCost(Instruction::AShr, Ty, CostKind, 647 Opd1Info, Opd2Info, 648 TargetTransformInfo::OP_None, 649 TargetTransformInfo::OP_None); 650 return MulCost * 2 + AddCost * 2 + ShrCost * 2 + 1; 651 } 652 } 653 654 Cost += BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info, 655 Opd2Info, 656 Opd1PropInfo, Opd2PropInfo); 657 if (Ty->isVectorTy()) { 658 // On AArch64, vector divisions are not supported natively and are 659 // expanded into scalar divisions of each pair of elements. 660 Cost += getArithmeticInstrCost(Instruction::ExtractElement, Ty, CostKind, 661 Opd1Info, Opd2Info, Opd1PropInfo, 662 Opd2PropInfo); 663 Cost += getArithmeticInstrCost(Instruction::InsertElement, Ty, CostKind, 664 Opd1Info, Opd2Info, Opd1PropInfo, 665 Opd2PropInfo); 666 // TODO: if one of the arguments is scalar, then it's not necessary to 667 // double the cost of handling the vector elements. 668 Cost += Cost; 669 } 670 return Cost; 671 672 case ISD::MUL: 673 if (LT.second != MVT::v2i64) 674 return (Cost + 1) * LT.first; 675 // Since we do not have a MUL.2d instruction, a mul <2 x i64> is expensive 676 // as elements are extracted from the vectors and the muls scalarized. 677 // As getScalarizationOverhead is a bit too pessimistic, we estimate the 678 // cost for a i64 vector directly here, which is: 679 // - four i64 extracts, 680 // - two i64 inserts, and 681 // - two muls. 682 // So, for a v2i64 with LT.First = 1 the cost is 8, and for a v4i64 with 683 // LT.first = 2 the cost is 16. 684 return LT.first * 8; 685 case ISD::ADD: 686 case ISD::XOR: 687 case ISD::OR: 688 case ISD::AND: 689 // These nodes are marked as 'custom' for combining purposes only. 690 // We know that they are legal. See LowerAdd in ISelLowering. 691 return (Cost + 1) * LT.first; 692 693 case ISD::FADD: 694 // These nodes are marked as 'custom' just to lower them to SVE. 695 // We know said lowering will incur no additional cost. 696 if (isa<FixedVectorType>(Ty) && !Ty->getScalarType()->isFP128Ty()) 697 return (Cost + 2) * LT.first; 698 699 return Cost + BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info, 700 Opd2Info, 701 Opd1PropInfo, Opd2PropInfo); 702 } 703 } 704 705 int AArch64TTIImpl::getAddressComputationCost(Type *Ty, ScalarEvolution *SE, 706 const SCEV *Ptr) { 707 // Address computations in vectorized code with non-consecutive addresses will 708 // likely result in more instructions compared to scalar code where the 709 // computation can more often be merged into the index mode. The resulting 710 // extra micro-ops can significantly decrease throughput. 711 unsigned NumVectorInstToHideOverhead = 10; 712 int MaxMergeDistance = 64; 713 714 if (Ty->isVectorTy() && SE && 715 !BaseT::isConstantStridedAccessLessThan(SE, Ptr, MaxMergeDistance + 1)) 716 return NumVectorInstToHideOverhead; 717 718 // In many cases the address computation is not merged into the instruction 719 // addressing mode. 720 return 1; 721 } 722 723 int AArch64TTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, 724 Type *CondTy, CmpInst::Predicate VecPred, 725 TTI::TargetCostKind CostKind, 726 const Instruction *I) { 727 // TODO: Handle other cost kinds. 728 if (CostKind != TTI::TCK_RecipThroughput) 729 return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind, 730 I); 731 732 int ISD = TLI->InstructionOpcodeToISD(Opcode); 733 // We don't lower some vector selects well that are wider than the register 734 // width. 735 if (isa<FixedVectorType>(ValTy) && ISD == ISD::SELECT) { 736 // We would need this many instructions to hide the scalarization happening. 737 const int AmortizationCost = 20; 738 739 // If VecPred is not set, check if we can get a predicate from the context 740 // instruction, if its type matches the requested ValTy. 741 if (VecPred == CmpInst::BAD_ICMP_PREDICATE && I && I->getType() == ValTy) { 742 CmpInst::Predicate CurrentPred; 743 if (match(I, m_Select(m_Cmp(CurrentPred, m_Value(), m_Value()), m_Value(), 744 m_Value()))) 745 VecPred = CurrentPred; 746 } 747 // Check if we have a compare/select chain that can be lowered using CMxx & 748 // BFI pair. 749 if (CmpInst::isIntPredicate(VecPred)) { 750 static const auto ValidMinMaxTys = {MVT::v8i8, MVT::v16i8, MVT::v4i16, 751 MVT::v8i16, MVT::v2i32, MVT::v4i32, 752 MVT::v2i64}; 753 auto LT = TLI->getTypeLegalizationCost(DL, ValTy); 754 if (any_of(ValidMinMaxTys, [<](MVT M) { return M == LT.second; })) 755 return LT.first; 756 } 757 758 static const TypeConversionCostTblEntry 759 VectorSelectTbl[] = { 760 { ISD::SELECT, MVT::v16i1, MVT::v16i16, 16 }, 761 { ISD::SELECT, MVT::v8i1, MVT::v8i32, 8 }, 762 { ISD::SELECT, MVT::v16i1, MVT::v16i32, 16 }, 763 { ISD::SELECT, MVT::v4i1, MVT::v4i64, 4 * AmortizationCost }, 764 { ISD::SELECT, MVT::v8i1, MVT::v8i64, 8 * AmortizationCost }, 765 { ISD::SELECT, MVT::v16i1, MVT::v16i64, 16 * AmortizationCost } 766 }; 767 768 EVT SelCondTy = TLI->getValueType(DL, CondTy); 769 EVT SelValTy = TLI->getValueType(DL, ValTy); 770 if (SelCondTy.isSimple() && SelValTy.isSimple()) { 771 if (const auto *Entry = ConvertCostTableLookup(VectorSelectTbl, ISD, 772 SelCondTy.getSimpleVT(), 773 SelValTy.getSimpleVT())) 774 return Entry->Cost; 775 } 776 } 777 // The base case handles scalable vectors fine for now, since it treats the 778 // cost as 1 * legalization cost. 779 return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind, I); 780 } 781 782 AArch64TTIImpl::TTI::MemCmpExpansionOptions 783 AArch64TTIImpl::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const { 784 TTI::MemCmpExpansionOptions Options; 785 if (ST->requiresStrictAlign()) { 786 // TODO: Add cost modeling for strict align. Misaligned loads expand to 787 // a bunch of instructions when strict align is enabled. 788 return Options; 789 } 790 Options.AllowOverlappingLoads = true; 791 Options.MaxNumLoads = TLI->getMaxExpandSizeMemcmp(OptSize); 792 Options.NumLoadsPerBlock = Options.MaxNumLoads; 793 // TODO: Though vector loads usually perform well on AArch64, in some targets 794 // they may wake up the FP unit, which raises the power consumption. Perhaps 795 // they could be used with no holds barred (-O3). 796 Options.LoadSizes = {8, 4, 2, 1}; 797 return Options; 798 } 799 800 unsigned AArch64TTIImpl::getGatherScatterOpCost( 801 unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask, 802 Align Alignment, TTI::TargetCostKind CostKind, const Instruction *I) { 803 804 if (!isa<ScalableVectorType>(DataTy)) 805 return BaseT::getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask, 806 Alignment, CostKind, I); 807 auto *VT = cast<VectorType>(DataTy); 808 auto LT = TLI->getTypeLegalizationCost(DL, DataTy); 809 ElementCount LegalVF = LT.second.getVectorElementCount(); 810 Optional<unsigned> MaxNumVScale = getMaxVScale(); 811 assert(MaxNumVScale && "Expected valid max vscale value"); 812 813 unsigned MemOpCost = 814 getMemoryOpCost(Opcode, VT->getElementType(), Alignment, 0, CostKind, I); 815 unsigned MaxNumElementsPerGather = 816 MaxNumVScale.getValue() * LegalVF.getKnownMinValue(); 817 return LT.first * MaxNumElementsPerGather * MemOpCost; 818 } 819 820 bool AArch64TTIImpl::useNeonVector(const Type *Ty) const { 821 return isa<FixedVectorType>(Ty) && !ST->useSVEForFixedLengthVectors(); 822 } 823 824 int AArch64TTIImpl::getMemoryOpCost(unsigned Opcode, Type *Ty, 825 MaybeAlign Alignment, unsigned AddressSpace, 826 TTI::TargetCostKind CostKind, 827 const Instruction *I) { 828 // TODO: Handle other cost kinds. 829 if (CostKind != TTI::TCK_RecipThroughput) 830 return 1; 831 832 // Type legalization can't handle structs 833 if (TLI->getValueType(DL, Ty, true) == MVT::Other) 834 return BaseT::getMemoryOpCost(Opcode, Ty, Alignment, AddressSpace, 835 CostKind); 836 837 auto LT = TLI->getTypeLegalizationCost(DL, Ty); 838 839 if (ST->isMisaligned128StoreSlow() && Opcode == Instruction::Store && 840 LT.second.is128BitVector() && (!Alignment || *Alignment < Align(16))) { 841 // Unaligned stores are extremely inefficient. We don't split all 842 // unaligned 128-bit stores because the negative impact that has shown in 843 // practice on inlined block copy code. 844 // We make such stores expensive so that we will only vectorize if there 845 // are 6 other instructions getting vectorized. 846 const int AmortizationCost = 6; 847 848 return LT.first * 2 * AmortizationCost; 849 } 850 851 if (useNeonVector(Ty) && 852 cast<VectorType>(Ty)->getElementType()->isIntegerTy(8)) { 853 unsigned ProfitableNumElements; 854 if (Opcode == Instruction::Store) 855 // We use a custom trunc store lowering so v.4b should be profitable. 856 ProfitableNumElements = 4; 857 else 858 // We scalarize the loads because there is not v.4b register and we 859 // have to promote the elements to v.2. 860 ProfitableNumElements = 8; 861 862 if (cast<FixedVectorType>(Ty)->getNumElements() < ProfitableNumElements) { 863 unsigned NumVecElts = cast<FixedVectorType>(Ty)->getNumElements(); 864 unsigned NumVectorizableInstsToAmortize = NumVecElts * 2; 865 // We generate 2 instructions per vector element. 866 return NumVectorizableInstsToAmortize * NumVecElts * 2; 867 } 868 } 869 870 return LT.first; 871 } 872 873 int AArch64TTIImpl::getInterleavedMemoryOpCost( 874 unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices, 875 Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, 876 bool UseMaskForCond, bool UseMaskForGaps) { 877 assert(Factor >= 2 && "Invalid interleave factor"); 878 auto *VecVTy = cast<FixedVectorType>(VecTy); 879 880 if (!UseMaskForCond && !UseMaskForGaps && 881 Factor <= TLI->getMaxSupportedInterleaveFactor()) { 882 unsigned NumElts = VecVTy->getNumElements(); 883 auto *SubVecTy = 884 FixedVectorType::get(VecTy->getScalarType(), NumElts / Factor); 885 886 // ldN/stN only support legal vector types of size 64 or 128 in bits. 887 // Accesses having vector types that are a multiple of 128 bits can be 888 // matched to more than one ldN/stN instruction. 889 if (NumElts % Factor == 0 && 890 TLI->isLegalInterleavedAccessType(SubVecTy, DL)) 891 return Factor * TLI->getNumInterleavedAccesses(SubVecTy, DL); 892 } 893 894 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices, 895 Alignment, AddressSpace, CostKind, 896 UseMaskForCond, UseMaskForGaps); 897 } 898 899 int AArch64TTIImpl::getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) { 900 int Cost = 0; 901 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput; 902 for (auto *I : Tys) { 903 if (!I->isVectorTy()) 904 continue; 905 if (I->getScalarSizeInBits() * cast<FixedVectorType>(I)->getNumElements() == 906 128) 907 Cost += getMemoryOpCost(Instruction::Store, I, Align(128), 0, CostKind) + 908 getMemoryOpCost(Instruction::Load, I, Align(128), 0, CostKind); 909 } 910 return Cost; 911 } 912 913 unsigned AArch64TTIImpl::getMaxInterleaveFactor(unsigned VF) { 914 return ST->getMaxInterleaveFactor(); 915 } 916 917 // For Falkor, we want to avoid having too many strided loads in a loop since 918 // that can exhaust the HW prefetcher resources. We adjust the unroller 919 // MaxCount preference below to attempt to ensure unrolling doesn't create too 920 // many strided loads. 921 static void 922 getFalkorUnrollingPreferences(Loop *L, ScalarEvolution &SE, 923 TargetTransformInfo::UnrollingPreferences &UP) { 924 enum { MaxStridedLoads = 7 }; 925 auto countStridedLoads = [](Loop *L, ScalarEvolution &SE) { 926 int StridedLoads = 0; 927 // FIXME? We could make this more precise by looking at the CFG and 928 // e.g. not counting loads in each side of an if-then-else diamond. 929 for (const auto BB : L->blocks()) { 930 for (auto &I : *BB) { 931 LoadInst *LMemI = dyn_cast<LoadInst>(&I); 932 if (!LMemI) 933 continue; 934 935 Value *PtrValue = LMemI->getPointerOperand(); 936 if (L->isLoopInvariant(PtrValue)) 937 continue; 938 939 const SCEV *LSCEV = SE.getSCEV(PtrValue); 940 const SCEVAddRecExpr *LSCEVAddRec = dyn_cast<SCEVAddRecExpr>(LSCEV); 941 if (!LSCEVAddRec || !LSCEVAddRec->isAffine()) 942 continue; 943 944 // FIXME? We could take pairing of unrolled load copies into account 945 // by looking at the AddRec, but we would probably have to limit this 946 // to loops with no stores or other memory optimization barriers. 947 ++StridedLoads; 948 // We've seen enough strided loads that seeing more won't make a 949 // difference. 950 if (StridedLoads > MaxStridedLoads / 2) 951 return StridedLoads; 952 } 953 } 954 return StridedLoads; 955 }; 956 957 int StridedLoads = countStridedLoads(L, SE); 958 LLVM_DEBUG(dbgs() << "falkor-hwpf: detected " << StridedLoads 959 << " strided loads\n"); 960 // Pick the largest power of 2 unroll count that won't result in too many 961 // strided loads. 962 if (StridedLoads) { 963 UP.MaxCount = 1 << Log2_32(MaxStridedLoads / StridedLoads); 964 LLVM_DEBUG(dbgs() << "falkor-hwpf: setting unroll MaxCount to " 965 << UP.MaxCount << '\n'); 966 } 967 } 968 969 void AArch64TTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE, 970 TTI::UnrollingPreferences &UP) { 971 // Enable partial unrolling and runtime unrolling. 972 BaseT::getUnrollingPreferences(L, SE, UP); 973 974 // For inner loop, it is more likely to be a hot one, and the runtime check 975 // can be promoted out from LICM pass, so the overhead is less, let's try 976 // a larger threshold to unroll more loops. 977 if (L->getLoopDepth() > 1) 978 UP.PartialThreshold *= 2; 979 980 // Disable partial & runtime unrolling on -Os. 981 UP.PartialOptSizeThreshold = 0; 982 983 if (ST->getProcFamily() == AArch64Subtarget::Falkor && 984 EnableFalkorHWPFUnrollFix) 985 getFalkorUnrollingPreferences(L, SE, UP); 986 } 987 988 void AArch64TTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE, 989 TTI::PeelingPreferences &PP) { 990 BaseT::getPeelingPreferences(L, SE, PP); 991 } 992 993 Value *AArch64TTIImpl::getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst, 994 Type *ExpectedType) { 995 switch (Inst->getIntrinsicID()) { 996 default: 997 return nullptr; 998 case Intrinsic::aarch64_neon_st2: 999 case Intrinsic::aarch64_neon_st3: 1000 case Intrinsic::aarch64_neon_st4: { 1001 // Create a struct type 1002 StructType *ST = dyn_cast<StructType>(ExpectedType); 1003 if (!ST) 1004 return nullptr; 1005 unsigned NumElts = Inst->getNumArgOperands() - 1; 1006 if (ST->getNumElements() != NumElts) 1007 return nullptr; 1008 for (unsigned i = 0, e = NumElts; i != e; ++i) { 1009 if (Inst->getArgOperand(i)->getType() != ST->getElementType(i)) 1010 return nullptr; 1011 } 1012 Value *Res = UndefValue::get(ExpectedType); 1013 IRBuilder<> Builder(Inst); 1014 for (unsigned i = 0, e = NumElts; i != e; ++i) { 1015 Value *L = Inst->getArgOperand(i); 1016 Res = Builder.CreateInsertValue(Res, L, i); 1017 } 1018 return Res; 1019 } 1020 case Intrinsic::aarch64_neon_ld2: 1021 case Intrinsic::aarch64_neon_ld3: 1022 case Intrinsic::aarch64_neon_ld4: 1023 if (Inst->getType() == ExpectedType) 1024 return Inst; 1025 return nullptr; 1026 } 1027 } 1028 1029 bool AArch64TTIImpl::getTgtMemIntrinsic(IntrinsicInst *Inst, 1030 MemIntrinsicInfo &Info) { 1031 switch (Inst->getIntrinsicID()) { 1032 default: 1033 break; 1034 case Intrinsic::aarch64_neon_ld2: 1035 case Intrinsic::aarch64_neon_ld3: 1036 case Intrinsic::aarch64_neon_ld4: 1037 Info.ReadMem = true; 1038 Info.WriteMem = false; 1039 Info.PtrVal = Inst->getArgOperand(0); 1040 break; 1041 case Intrinsic::aarch64_neon_st2: 1042 case Intrinsic::aarch64_neon_st3: 1043 case Intrinsic::aarch64_neon_st4: 1044 Info.ReadMem = false; 1045 Info.WriteMem = true; 1046 Info.PtrVal = Inst->getArgOperand(Inst->getNumArgOperands() - 1); 1047 break; 1048 } 1049 1050 switch (Inst->getIntrinsicID()) { 1051 default: 1052 return false; 1053 case Intrinsic::aarch64_neon_ld2: 1054 case Intrinsic::aarch64_neon_st2: 1055 Info.MatchingId = VECTOR_LDST_TWO_ELEMENTS; 1056 break; 1057 case Intrinsic::aarch64_neon_ld3: 1058 case Intrinsic::aarch64_neon_st3: 1059 Info.MatchingId = VECTOR_LDST_THREE_ELEMENTS; 1060 break; 1061 case Intrinsic::aarch64_neon_ld4: 1062 case Intrinsic::aarch64_neon_st4: 1063 Info.MatchingId = VECTOR_LDST_FOUR_ELEMENTS; 1064 break; 1065 } 1066 return true; 1067 } 1068 1069 /// See if \p I should be considered for address type promotion. We check if \p 1070 /// I is a sext with right type and used in memory accesses. If it used in a 1071 /// "complex" getelementptr, we allow it to be promoted without finding other 1072 /// sext instructions that sign extended the same initial value. A getelementptr 1073 /// is considered as "complex" if it has more than 2 operands. 1074 bool AArch64TTIImpl::shouldConsiderAddressTypePromotion( 1075 const Instruction &I, bool &AllowPromotionWithoutCommonHeader) { 1076 bool Considerable = false; 1077 AllowPromotionWithoutCommonHeader = false; 1078 if (!isa<SExtInst>(&I)) 1079 return false; 1080 Type *ConsideredSExtType = 1081 Type::getInt64Ty(I.getParent()->getParent()->getContext()); 1082 if (I.getType() != ConsideredSExtType) 1083 return false; 1084 // See if the sext is the one with the right type and used in at least one 1085 // GetElementPtrInst. 1086 for (const User *U : I.users()) { 1087 if (const GetElementPtrInst *GEPInst = dyn_cast<GetElementPtrInst>(U)) { 1088 Considerable = true; 1089 // A getelementptr is considered as "complex" if it has more than 2 1090 // operands. We will promote a SExt used in such complex GEP as we 1091 // expect some computation to be merged if they are done on 64 bits. 1092 if (GEPInst->getNumOperands() > 2) { 1093 AllowPromotionWithoutCommonHeader = true; 1094 break; 1095 } 1096 } 1097 } 1098 return Considerable; 1099 } 1100 1101 bool AArch64TTIImpl::isLegalToVectorizeReduction(RecurrenceDescriptor RdxDesc, 1102 ElementCount VF) const { 1103 if (!VF.isScalable()) 1104 return true; 1105 1106 Type *Ty = RdxDesc.getRecurrenceType(); 1107 if (Ty->isBFloatTy() || !isLegalElementTypeForSVE(Ty)) 1108 return false; 1109 1110 switch (RdxDesc.getRecurrenceKind()) { 1111 case RecurKind::Add: 1112 case RecurKind::FAdd: 1113 case RecurKind::And: 1114 case RecurKind::Or: 1115 case RecurKind::Xor: 1116 case RecurKind::SMin: 1117 case RecurKind::SMax: 1118 case RecurKind::UMin: 1119 case RecurKind::UMax: 1120 case RecurKind::FMin: 1121 case RecurKind::FMax: 1122 return true; 1123 default: 1124 return false; 1125 } 1126 } 1127 1128 int AArch64TTIImpl::getMinMaxReductionCost(VectorType *Ty, VectorType *CondTy, 1129 bool IsPairwise, bool IsUnsigned, 1130 TTI::TargetCostKind CostKind) { 1131 if (!isa<ScalableVectorType>(Ty)) 1132 return BaseT::getMinMaxReductionCost(Ty, CondTy, IsPairwise, IsUnsigned, 1133 CostKind); 1134 assert((isa<ScalableVectorType>(Ty) && isa<ScalableVectorType>(CondTy)) && 1135 "Both vector needs to be scalable"); 1136 1137 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 1138 int LegalizationCost = 0; 1139 if (LT.first > 1) { 1140 Type *LegalVTy = EVT(LT.second).getTypeForEVT(Ty->getContext()); 1141 unsigned CmpOpcode = 1142 Ty->isFPOrFPVectorTy() ? Instruction::FCmp : Instruction::ICmp; 1143 LegalizationCost = 1144 getCmpSelInstrCost(CmpOpcode, LegalVTy, LegalVTy, 1145 CmpInst::BAD_ICMP_PREDICATE, CostKind) + 1146 getCmpSelInstrCost(Instruction::Select, LegalVTy, LegalVTy, 1147 CmpInst::BAD_ICMP_PREDICATE, CostKind); 1148 LegalizationCost *= LT.first - 1; 1149 } 1150 1151 return LegalizationCost + /*Cost of horizontal reduction*/ 2; 1152 } 1153 1154 int AArch64TTIImpl::getArithmeticReductionCostSVE( 1155 unsigned Opcode, VectorType *ValTy, bool IsPairwise, 1156 TTI::TargetCostKind CostKind) { 1157 assert(!IsPairwise && "Cannot be pair wise to continue"); 1158 1159 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy); 1160 int LegalizationCost = 0; 1161 if (LT.first > 1) { 1162 Type *LegalVTy = EVT(LT.second).getTypeForEVT(ValTy->getContext()); 1163 LegalizationCost = getArithmeticInstrCost(Opcode, LegalVTy, CostKind); 1164 LegalizationCost *= LT.first - 1; 1165 } 1166 1167 int ISD = TLI->InstructionOpcodeToISD(Opcode); 1168 assert(ISD && "Invalid opcode"); 1169 // Add the final reduction cost for the legal horizontal reduction 1170 switch (ISD) { 1171 case ISD::ADD: 1172 case ISD::AND: 1173 case ISD::OR: 1174 case ISD::XOR: 1175 case ISD::FADD: 1176 return LegalizationCost + 2; 1177 default: 1178 // TODO: Replace for invalid when InstructionCost is used 1179 // cases not supported by SVE 1180 return 16; 1181 } 1182 } 1183 1184 int AArch64TTIImpl::getArithmeticReductionCost(unsigned Opcode, 1185 VectorType *ValTy, 1186 bool IsPairwiseForm, 1187 TTI::TargetCostKind CostKind) { 1188 1189 if (isa<ScalableVectorType>(ValTy)) 1190 return getArithmeticReductionCostSVE(Opcode, ValTy, IsPairwiseForm, 1191 CostKind); 1192 if (IsPairwiseForm) 1193 return BaseT::getArithmeticReductionCost(Opcode, ValTy, IsPairwiseForm, 1194 CostKind); 1195 1196 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy); 1197 MVT MTy = LT.second; 1198 int ISD = TLI->InstructionOpcodeToISD(Opcode); 1199 assert(ISD && "Invalid opcode"); 1200 1201 // Horizontal adds can use the 'addv' instruction. We model the cost of these 1202 // instructions as normal vector adds. This is the only arithmetic vector 1203 // reduction operation for which we have an instruction. 1204 static const CostTblEntry CostTblNoPairwise[]{ 1205 {ISD::ADD, MVT::v8i8, 1}, 1206 {ISD::ADD, MVT::v16i8, 1}, 1207 {ISD::ADD, MVT::v4i16, 1}, 1208 {ISD::ADD, MVT::v8i16, 1}, 1209 {ISD::ADD, MVT::v4i32, 1}, 1210 }; 1211 1212 if (const auto *Entry = CostTableLookup(CostTblNoPairwise, ISD, MTy)) 1213 return LT.first * Entry->Cost; 1214 1215 return BaseT::getArithmeticReductionCost(Opcode, ValTy, IsPairwiseForm, 1216 CostKind); 1217 } 1218 1219 int AArch64TTIImpl::getShuffleCost(TTI::ShuffleKind Kind, VectorType *Tp, 1220 ArrayRef<int> Mask, int Index, 1221 VectorType *SubTp) { 1222 if (Kind == TTI::SK_Broadcast || Kind == TTI::SK_Transpose || 1223 Kind == TTI::SK_Select || Kind == TTI::SK_PermuteSingleSrc || 1224 Kind == TTI::SK_Reverse) { 1225 static const CostTblEntry ShuffleTbl[] = { 1226 // Broadcast shuffle kinds can be performed with 'dup'. 1227 { TTI::SK_Broadcast, MVT::v8i8, 1 }, 1228 { TTI::SK_Broadcast, MVT::v16i8, 1 }, 1229 { TTI::SK_Broadcast, MVT::v4i16, 1 }, 1230 { TTI::SK_Broadcast, MVT::v8i16, 1 }, 1231 { TTI::SK_Broadcast, MVT::v2i32, 1 }, 1232 { TTI::SK_Broadcast, MVT::v4i32, 1 }, 1233 { TTI::SK_Broadcast, MVT::v2i64, 1 }, 1234 { TTI::SK_Broadcast, MVT::v2f32, 1 }, 1235 { TTI::SK_Broadcast, MVT::v4f32, 1 }, 1236 { TTI::SK_Broadcast, MVT::v2f64, 1 }, 1237 // Transpose shuffle kinds can be performed with 'trn1/trn2' and 1238 // 'zip1/zip2' instructions. 1239 { TTI::SK_Transpose, MVT::v8i8, 1 }, 1240 { TTI::SK_Transpose, MVT::v16i8, 1 }, 1241 { TTI::SK_Transpose, MVT::v4i16, 1 }, 1242 { TTI::SK_Transpose, MVT::v8i16, 1 }, 1243 { TTI::SK_Transpose, MVT::v2i32, 1 }, 1244 { TTI::SK_Transpose, MVT::v4i32, 1 }, 1245 { TTI::SK_Transpose, MVT::v2i64, 1 }, 1246 { TTI::SK_Transpose, MVT::v2f32, 1 }, 1247 { TTI::SK_Transpose, MVT::v4f32, 1 }, 1248 { TTI::SK_Transpose, MVT::v2f64, 1 }, 1249 // Select shuffle kinds. 1250 // TODO: handle vXi8/vXi16. 1251 { TTI::SK_Select, MVT::v2i32, 1 }, // mov. 1252 { TTI::SK_Select, MVT::v4i32, 2 }, // rev+trn (or similar). 1253 { TTI::SK_Select, MVT::v2i64, 1 }, // mov. 1254 { TTI::SK_Select, MVT::v2f32, 1 }, // mov. 1255 { TTI::SK_Select, MVT::v4f32, 2 }, // rev+trn (or similar). 1256 { TTI::SK_Select, MVT::v2f64, 1 }, // mov. 1257 // PermuteSingleSrc shuffle kinds. 1258 // TODO: handle vXi8/vXi16. 1259 { TTI::SK_PermuteSingleSrc, MVT::v2i32, 1 }, // mov. 1260 { TTI::SK_PermuteSingleSrc, MVT::v4i32, 3 }, // perfectshuffle worst case. 1261 { TTI::SK_PermuteSingleSrc, MVT::v2i64, 1 }, // mov. 1262 { TTI::SK_PermuteSingleSrc, MVT::v2f32, 1 }, // mov. 1263 { TTI::SK_PermuteSingleSrc, MVT::v4f32, 3 }, // perfectshuffle worst case. 1264 { TTI::SK_PermuteSingleSrc, MVT::v2f64, 1 }, // mov. 1265 // Broadcast shuffle kinds for scalable vectors 1266 { TTI::SK_Broadcast, MVT::nxv16i8, 1 }, 1267 { TTI::SK_Broadcast, MVT::nxv8i16, 1 }, 1268 { TTI::SK_Broadcast, MVT::nxv4i32, 1 }, 1269 { TTI::SK_Broadcast, MVT::nxv2i64, 1 }, 1270 { TTI::SK_Broadcast, MVT::nxv8f16, 1 }, 1271 { TTI::SK_Broadcast, MVT::nxv8bf16, 1 }, 1272 { TTI::SK_Broadcast, MVT::nxv4f32, 1 }, 1273 { TTI::SK_Broadcast, MVT::nxv2f64, 1 }, 1274 // Handle the cases for vector.reverse with scalable vectors 1275 { TTI::SK_Reverse, MVT::nxv16i8, 1 }, 1276 { TTI::SK_Reverse, MVT::nxv8i16, 1 }, 1277 { TTI::SK_Reverse, MVT::nxv4i32, 1 }, 1278 { TTI::SK_Reverse, MVT::nxv2i64, 1 }, 1279 { TTI::SK_Reverse, MVT::nxv8f16, 1 }, 1280 { TTI::SK_Reverse, MVT::nxv8bf16, 1 }, 1281 { TTI::SK_Reverse, MVT::nxv4f32, 1 }, 1282 { TTI::SK_Reverse, MVT::nxv2f64, 1 }, 1283 { TTI::SK_Reverse, MVT::nxv16i1, 1 }, 1284 { TTI::SK_Reverse, MVT::nxv8i1, 1 }, 1285 { TTI::SK_Reverse, MVT::nxv4i1, 1 }, 1286 { TTI::SK_Reverse, MVT::nxv2i1, 1 }, 1287 }; 1288 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp); 1289 if (const auto *Entry = CostTableLookup(ShuffleTbl, Kind, LT.second)) 1290 return LT.first * Entry->Cost; 1291 } 1292 1293 return BaseT::getShuffleCost(Kind, Tp, Mask, Index, SubTp); 1294 } 1295