1 //===- ARMTargetTransformInfo.cpp - ARM 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 "ARMTargetTransformInfo.h" 10 #include "ARMSubtarget.h" 11 #include "MCTargetDesc/ARMAddressingModes.h" 12 #include "llvm/ADT/APInt.h" 13 #include "llvm/ADT/SmallVector.h" 14 #include "llvm/Analysis/LoopInfo.h" 15 #include "llvm/CodeGen/CostTable.h" 16 #include "llvm/CodeGen/ISDOpcodes.h" 17 #include "llvm/CodeGen/ValueTypes.h" 18 #include "llvm/IR/BasicBlock.h" 19 #include "llvm/IR/DataLayout.h" 20 #include "llvm/IR/DerivedTypes.h" 21 #include "llvm/IR/Instruction.h" 22 #include "llvm/IR/Instructions.h" 23 #include "llvm/IR/IntrinsicInst.h" 24 #include "llvm/IR/IntrinsicsARM.h" 25 #include "llvm/IR/PatternMatch.h" 26 #include "llvm/IR/Type.h" 27 #include "llvm/MC/SubtargetFeature.h" 28 #include "llvm/Support/Casting.h" 29 #include "llvm/Support/KnownBits.h" 30 #include "llvm/Support/MachineValueType.h" 31 #include "llvm/Target/TargetMachine.h" 32 #include "llvm/Transforms/InstCombine/InstCombiner.h" 33 #include "llvm/Transforms/Utils/Local.h" 34 #include "llvm/Transforms/Utils/LoopUtils.h" 35 #include <algorithm> 36 #include <cassert> 37 #include <cstdint> 38 #include <utility> 39 40 using namespace llvm; 41 42 #define DEBUG_TYPE "armtti" 43 44 static cl::opt<bool> EnableMaskedLoadStores( 45 "enable-arm-maskedldst", cl::Hidden, cl::init(true), 46 cl::desc("Enable the generation of masked loads and stores")); 47 48 static cl::opt<bool> DisableLowOverheadLoops( 49 "disable-arm-loloops", cl::Hidden, cl::init(false), 50 cl::desc("Disable the generation of low-overhead loops")); 51 52 extern cl::opt<TailPredication::Mode> EnableTailPredication; 53 54 extern cl::opt<bool> EnableMaskedGatherScatters; 55 56 extern cl::opt<unsigned> MVEMaxSupportedInterleaveFactor; 57 58 /// Convert a vector load intrinsic into a simple llvm load instruction. 59 /// This is beneficial when the underlying object being addressed comes 60 /// from a constant, since we get constant-folding for free. 61 static Value *simplifyNeonVld1(const IntrinsicInst &II, unsigned MemAlign, 62 InstCombiner::BuilderTy &Builder) { 63 auto *IntrAlign = dyn_cast<ConstantInt>(II.getArgOperand(1)); 64 65 if (!IntrAlign) 66 return nullptr; 67 68 unsigned Alignment = IntrAlign->getLimitedValue() < MemAlign 69 ? MemAlign 70 : IntrAlign->getLimitedValue(); 71 72 if (!isPowerOf2_32(Alignment)) 73 return nullptr; 74 75 auto *BCastInst = Builder.CreateBitCast(II.getArgOperand(0), 76 PointerType::get(II.getType(), 0)); 77 return Builder.CreateAlignedLoad(II.getType(), BCastInst, Align(Alignment)); 78 } 79 80 bool ARMTTIImpl::areInlineCompatible(const Function *Caller, 81 const Function *Callee) const { 82 const TargetMachine &TM = getTLI()->getTargetMachine(); 83 const FeatureBitset &CallerBits = 84 TM.getSubtargetImpl(*Caller)->getFeatureBits(); 85 const FeatureBitset &CalleeBits = 86 TM.getSubtargetImpl(*Callee)->getFeatureBits(); 87 88 // To inline a callee, all features not in the allowed list must match exactly. 89 bool MatchExact = (CallerBits & ~InlineFeaturesAllowed) == 90 (CalleeBits & ~InlineFeaturesAllowed); 91 // For features in the allowed list, the callee's features must be a subset of 92 // the callers'. 93 bool MatchSubset = ((CallerBits & CalleeBits) & InlineFeaturesAllowed) == 94 (CalleeBits & InlineFeaturesAllowed); 95 return MatchExact && MatchSubset; 96 } 97 98 bool ARMTTIImpl::shouldFavorBackedgeIndex(const Loop *L) const { 99 if (L->getHeader()->getParent()->hasOptSize()) 100 return false; 101 if (ST->hasMVEIntegerOps()) 102 return false; 103 return ST->isMClass() && ST->isThumb2() && L->getNumBlocks() == 1; 104 } 105 106 bool ARMTTIImpl::shouldFavorPostInc() const { 107 if (ST->hasMVEIntegerOps()) 108 return true; 109 return false; 110 } 111 112 Optional<Instruction *> 113 ARMTTIImpl::instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const { 114 using namespace PatternMatch; 115 Intrinsic::ID IID = II.getIntrinsicID(); 116 switch (IID) { 117 default: 118 break; 119 case Intrinsic::arm_neon_vld1: { 120 Align MemAlign = 121 getKnownAlignment(II.getArgOperand(0), IC.getDataLayout(), &II, 122 &IC.getAssumptionCache(), &IC.getDominatorTree()); 123 if (Value *V = simplifyNeonVld1(II, MemAlign.value(), IC.Builder)) { 124 return IC.replaceInstUsesWith(II, V); 125 } 126 break; 127 } 128 129 case Intrinsic::arm_neon_vld2: 130 case Intrinsic::arm_neon_vld3: 131 case Intrinsic::arm_neon_vld4: 132 case Intrinsic::arm_neon_vld2lane: 133 case Intrinsic::arm_neon_vld3lane: 134 case Intrinsic::arm_neon_vld4lane: 135 case Intrinsic::arm_neon_vst1: 136 case Intrinsic::arm_neon_vst2: 137 case Intrinsic::arm_neon_vst3: 138 case Intrinsic::arm_neon_vst4: 139 case Intrinsic::arm_neon_vst2lane: 140 case Intrinsic::arm_neon_vst3lane: 141 case Intrinsic::arm_neon_vst4lane: { 142 Align MemAlign = 143 getKnownAlignment(II.getArgOperand(0), IC.getDataLayout(), &II, 144 &IC.getAssumptionCache(), &IC.getDominatorTree()); 145 unsigned AlignArg = II.getNumArgOperands() - 1; 146 Value *AlignArgOp = II.getArgOperand(AlignArg); 147 MaybeAlign Align = cast<ConstantInt>(AlignArgOp)->getMaybeAlignValue(); 148 if (Align && *Align < MemAlign) { 149 return IC.replaceOperand( 150 II, AlignArg, 151 ConstantInt::get(Type::getInt32Ty(II.getContext()), MemAlign.value(), 152 false)); 153 } 154 break; 155 } 156 157 case Intrinsic::arm_mve_pred_i2v: { 158 Value *Arg = II.getArgOperand(0); 159 Value *ArgArg; 160 if (match(Arg, PatternMatch::m_Intrinsic<Intrinsic::arm_mve_pred_v2i>( 161 PatternMatch::m_Value(ArgArg))) && 162 II.getType() == ArgArg->getType()) { 163 return IC.replaceInstUsesWith(II, ArgArg); 164 } 165 Constant *XorMask; 166 if (match(Arg, m_Xor(PatternMatch::m_Intrinsic<Intrinsic::arm_mve_pred_v2i>( 167 PatternMatch::m_Value(ArgArg)), 168 PatternMatch::m_Constant(XorMask))) && 169 II.getType() == ArgArg->getType()) { 170 if (auto *CI = dyn_cast<ConstantInt>(XorMask)) { 171 if (CI->getValue().trunc(16).isAllOnesValue()) { 172 auto TrueVector = IC.Builder.CreateVectorSplat( 173 cast<FixedVectorType>(II.getType())->getNumElements(), 174 IC.Builder.getTrue()); 175 return BinaryOperator::Create(Instruction::Xor, ArgArg, TrueVector); 176 } 177 } 178 } 179 KnownBits ScalarKnown(32); 180 if (IC.SimplifyDemandedBits(&II, 0, APInt::getLowBitsSet(32, 16), 181 ScalarKnown, 0)) { 182 return &II; 183 } 184 break; 185 } 186 case Intrinsic::arm_mve_pred_v2i: { 187 Value *Arg = II.getArgOperand(0); 188 Value *ArgArg; 189 if (match(Arg, PatternMatch::m_Intrinsic<Intrinsic::arm_mve_pred_i2v>( 190 PatternMatch::m_Value(ArgArg)))) { 191 return IC.replaceInstUsesWith(II, ArgArg); 192 } 193 if (!II.getMetadata(LLVMContext::MD_range)) { 194 Type *IntTy32 = Type::getInt32Ty(II.getContext()); 195 Metadata *M[] = { 196 ConstantAsMetadata::get(ConstantInt::get(IntTy32, 0)), 197 ConstantAsMetadata::get(ConstantInt::get(IntTy32, 0xFFFF))}; 198 II.setMetadata(LLVMContext::MD_range, MDNode::get(II.getContext(), M)); 199 return &II; 200 } 201 break; 202 } 203 case Intrinsic::arm_mve_vadc: 204 case Intrinsic::arm_mve_vadc_predicated: { 205 unsigned CarryOp = 206 (II.getIntrinsicID() == Intrinsic::arm_mve_vadc_predicated) ? 3 : 2; 207 assert(II.getArgOperand(CarryOp)->getType()->getScalarSizeInBits() == 32 && 208 "Bad type for intrinsic!"); 209 210 KnownBits CarryKnown(32); 211 if (IC.SimplifyDemandedBits(&II, CarryOp, APInt::getOneBitSet(32, 29), 212 CarryKnown)) { 213 return &II; 214 } 215 break; 216 } 217 case Intrinsic::arm_mve_vmldava: { 218 Instruction *I = cast<Instruction>(&II); 219 if (I->hasOneUse()) { 220 auto *User = cast<Instruction>(*I->user_begin()); 221 Value *OpZ; 222 if (match(User, m_c_Add(m_Specific(I), m_Value(OpZ))) && 223 match(I->getOperand(3), m_Zero())) { 224 Value *OpX = I->getOperand(4); 225 Value *OpY = I->getOperand(5); 226 Type *OpTy = OpX->getType(); 227 228 IC.Builder.SetInsertPoint(User); 229 Value *V = 230 IC.Builder.CreateIntrinsic(Intrinsic::arm_mve_vmldava, {OpTy}, 231 {I->getOperand(0), I->getOperand(1), 232 I->getOperand(2), OpZ, OpX, OpY}); 233 234 IC.replaceInstUsesWith(*User, V); 235 return IC.eraseInstFromFunction(*User); 236 } 237 } 238 return None; 239 } 240 } 241 return None; 242 } 243 244 int ARMTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty, 245 TTI::TargetCostKind CostKind) { 246 assert(Ty->isIntegerTy()); 247 248 unsigned Bits = Ty->getPrimitiveSizeInBits(); 249 if (Bits == 0 || Imm.getActiveBits() >= 64) 250 return 4; 251 252 int64_t SImmVal = Imm.getSExtValue(); 253 uint64_t ZImmVal = Imm.getZExtValue(); 254 if (!ST->isThumb()) { 255 if ((SImmVal >= 0 && SImmVal < 65536) || 256 (ARM_AM::getSOImmVal(ZImmVal) != -1) || 257 (ARM_AM::getSOImmVal(~ZImmVal) != -1)) 258 return 1; 259 return ST->hasV6T2Ops() ? 2 : 3; 260 } 261 if (ST->isThumb2()) { 262 if ((SImmVal >= 0 && SImmVal < 65536) || 263 (ARM_AM::getT2SOImmVal(ZImmVal) != -1) || 264 (ARM_AM::getT2SOImmVal(~ZImmVal) != -1)) 265 return 1; 266 return ST->hasV6T2Ops() ? 2 : 3; 267 } 268 // Thumb1, any i8 imm cost 1. 269 if (Bits == 8 || (SImmVal >= 0 && SImmVal < 256)) 270 return 1; 271 if ((~SImmVal < 256) || ARM_AM::isThumbImmShiftedVal(ZImmVal)) 272 return 2; 273 // Load from constantpool. 274 return 3; 275 } 276 277 // Constants smaller than 256 fit in the immediate field of 278 // Thumb1 instructions so we return a zero cost and 1 otherwise. 279 int ARMTTIImpl::getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx, 280 const APInt &Imm, Type *Ty) { 281 if (Imm.isNonNegative() && Imm.getLimitedValue() < 256) 282 return 0; 283 284 return 1; 285 } 286 287 // Checks whether Inst is part of a min(max()) or max(min()) pattern 288 // that will match to an SSAT instruction 289 static bool isSSATMinMaxPattern(Instruction *Inst, const APInt &Imm) { 290 Value *LHS, *RHS; 291 ConstantInt *C; 292 SelectPatternFlavor InstSPF = matchSelectPattern(Inst, LHS, RHS).Flavor; 293 294 if (InstSPF == SPF_SMAX && 295 PatternMatch::match(RHS, PatternMatch::m_ConstantInt(C)) && 296 C->getValue() == Imm && Imm.isNegative() && (-Imm).isPowerOf2()) { 297 298 auto isSSatMin = [&](Value *MinInst) { 299 if (isa<SelectInst>(MinInst)) { 300 Value *MinLHS, *MinRHS; 301 ConstantInt *MinC; 302 SelectPatternFlavor MinSPF = 303 matchSelectPattern(MinInst, MinLHS, MinRHS).Flavor; 304 if (MinSPF == SPF_SMIN && 305 PatternMatch::match(MinRHS, PatternMatch::m_ConstantInt(MinC)) && 306 MinC->getValue() == ((-Imm) - 1)) 307 return true; 308 } 309 return false; 310 }; 311 312 if (isSSatMin(Inst->getOperand(1)) || 313 (Inst->hasNUses(2) && (isSSatMin(*Inst->user_begin()) || 314 isSSatMin(*(++Inst->user_begin()))))) 315 return true; 316 } 317 return false; 318 } 319 320 int ARMTTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx, 321 const APInt &Imm, Type *Ty, 322 TTI::TargetCostKind CostKind, 323 Instruction *Inst) { 324 // Division by a constant can be turned into multiplication, but only if we 325 // know it's constant. So it's not so much that the immediate is cheap (it's 326 // not), but that the alternative is worse. 327 // FIXME: this is probably unneeded with GlobalISel. 328 if ((Opcode == Instruction::SDiv || Opcode == Instruction::UDiv || 329 Opcode == Instruction::SRem || Opcode == Instruction::URem) && 330 Idx == 1) 331 return 0; 332 333 if (Opcode == Instruction::And) { 334 // UXTB/UXTH 335 if (Imm == 255 || Imm == 65535) 336 return 0; 337 // Conversion to BIC is free, and means we can use ~Imm instead. 338 return std::min(getIntImmCost(Imm, Ty, CostKind), 339 getIntImmCost(~Imm, Ty, CostKind)); 340 } 341 342 if (Opcode == Instruction::Add) 343 // Conversion to SUB is free, and means we can use -Imm instead. 344 return std::min(getIntImmCost(Imm, Ty, CostKind), 345 getIntImmCost(-Imm, Ty, CostKind)); 346 347 if (Opcode == Instruction::ICmp && Imm.isNegative() && 348 Ty->getIntegerBitWidth() == 32) { 349 int64_t NegImm = -Imm.getSExtValue(); 350 if (ST->isThumb2() && NegImm < 1<<12) 351 // icmp X, #-C -> cmn X, #C 352 return 0; 353 if (ST->isThumb() && NegImm < 1<<8) 354 // icmp X, #-C -> adds X, #C 355 return 0; 356 } 357 358 // xor a, -1 can always be folded to MVN 359 if (Opcode == Instruction::Xor && Imm.isAllOnesValue()) 360 return 0; 361 362 // Ensures negative constant of min(max()) or max(min()) patterns that 363 // match to SSAT instructions don't get hoisted 364 if (Inst && ((ST->hasV6Ops() && !ST->isThumb()) || ST->isThumb2()) && 365 Ty->getIntegerBitWidth() <= 32 && isSSATMinMaxPattern(Inst, Imm)) 366 return 0; 367 368 return getIntImmCost(Imm, Ty, CostKind); 369 } 370 371 int ARMTTIImpl::getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind) { 372 if (CostKind == TTI::TCK_RecipThroughput && 373 (ST->hasNEON() || ST->hasMVEIntegerOps())) { 374 // FIXME: The vectorizer is highly sensistive to the cost of these 375 // instructions, which suggests that it may be using the costs incorrectly. 376 // But, for now, just make them free to avoid performance regressions for 377 // vector targets. 378 return 0; 379 } 380 return BaseT::getCFInstrCost(Opcode, CostKind); 381 } 382 383 int ARMTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, 384 TTI::CastContextHint CCH, 385 TTI::TargetCostKind CostKind, 386 const Instruction *I) { 387 int ISD = TLI->InstructionOpcodeToISD(Opcode); 388 assert(ISD && "Invalid opcode"); 389 390 // TODO: Allow non-throughput costs that aren't binary. 391 auto AdjustCost = [&CostKind](int Cost) { 392 if (CostKind != TTI::TCK_RecipThroughput) 393 return Cost == 0 ? 0 : 1; 394 return Cost; 395 }; 396 auto IsLegalFPType = [this](EVT VT) { 397 EVT EltVT = VT.getScalarType(); 398 return (EltVT == MVT::f32 && ST->hasVFP2Base()) || 399 (EltVT == MVT::f64 && ST->hasFP64()) || 400 (EltVT == MVT::f16 && ST->hasFullFP16()); 401 }; 402 403 EVT SrcTy = TLI->getValueType(DL, Src); 404 EVT DstTy = TLI->getValueType(DL, Dst); 405 406 if (!SrcTy.isSimple() || !DstTy.isSimple()) 407 return AdjustCost( 408 BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I)); 409 410 // Extending masked load/Truncating masked stores is expensive because we 411 // currently don't split them. This means that we'll likely end up 412 // loading/storing each element individually (hence the high cost). 413 if ((ST->hasMVEIntegerOps() && 414 (Opcode == Instruction::Trunc || Opcode == Instruction::ZExt || 415 Opcode == Instruction::SExt)) || 416 (ST->hasMVEFloatOps() && 417 (Opcode == Instruction::FPExt || Opcode == Instruction::FPTrunc) && 418 IsLegalFPType(SrcTy) && IsLegalFPType(DstTy))) 419 if (CCH == TTI::CastContextHint::Masked && DstTy.getSizeInBits() > 128) 420 return 2 * DstTy.getVectorNumElements() * ST->getMVEVectorCostFactor(); 421 422 // The extend of other kinds of load is free 423 if (CCH == TTI::CastContextHint::Normal || 424 CCH == TTI::CastContextHint::Masked) { 425 static const TypeConversionCostTblEntry LoadConversionTbl[] = { 426 {ISD::SIGN_EXTEND, MVT::i32, MVT::i16, 0}, 427 {ISD::ZERO_EXTEND, MVT::i32, MVT::i16, 0}, 428 {ISD::SIGN_EXTEND, MVT::i32, MVT::i8, 0}, 429 {ISD::ZERO_EXTEND, MVT::i32, MVT::i8, 0}, 430 {ISD::SIGN_EXTEND, MVT::i16, MVT::i8, 0}, 431 {ISD::ZERO_EXTEND, MVT::i16, MVT::i8, 0}, 432 {ISD::SIGN_EXTEND, MVT::i64, MVT::i32, 1}, 433 {ISD::ZERO_EXTEND, MVT::i64, MVT::i32, 1}, 434 {ISD::SIGN_EXTEND, MVT::i64, MVT::i16, 1}, 435 {ISD::ZERO_EXTEND, MVT::i64, MVT::i16, 1}, 436 {ISD::SIGN_EXTEND, MVT::i64, MVT::i8, 1}, 437 {ISD::ZERO_EXTEND, MVT::i64, MVT::i8, 1}, 438 }; 439 if (const auto *Entry = ConvertCostTableLookup( 440 LoadConversionTbl, ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT())) 441 return AdjustCost(Entry->Cost); 442 443 static const TypeConversionCostTblEntry MVELoadConversionTbl[] = { 444 {ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 0}, 445 {ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 0}, 446 {ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 0}, 447 {ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 0}, 448 {ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 0}, 449 {ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 0}, 450 // The following extend from a legal type to an illegal type, so need to 451 // split the load. This introduced an extra load operation, but the 452 // extend is still "free". 453 {ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 1}, 454 {ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 1}, 455 {ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 3}, 456 {ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 3}, 457 {ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 1}, 458 {ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 1}, 459 }; 460 if (SrcTy.isVector() && ST->hasMVEIntegerOps()) { 461 if (const auto *Entry = 462 ConvertCostTableLookup(MVELoadConversionTbl, ISD, 463 DstTy.getSimpleVT(), SrcTy.getSimpleVT())) 464 return AdjustCost(Entry->Cost * ST->getMVEVectorCostFactor()); 465 } 466 467 static const TypeConversionCostTblEntry MVEFLoadConversionTbl[] = { 468 // FPExtends are similar but also require the VCVT instructions. 469 {ISD::FP_EXTEND, MVT::v4f32, MVT::v4f16, 1}, 470 {ISD::FP_EXTEND, MVT::v8f32, MVT::v8f16, 3}, 471 }; 472 if (SrcTy.isVector() && ST->hasMVEFloatOps()) { 473 if (const auto *Entry = 474 ConvertCostTableLookup(MVEFLoadConversionTbl, ISD, 475 DstTy.getSimpleVT(), SrcTy.getSimpleVT())) 476 return AdjustCost(Entry->Cost * ST->getMVEVectorCostFactor()); 477 } 478 479 // The truncate of a store is free. This is the mirror of extends above. 480 static const TypeConversionCostTblEntry MVEStoreConversionTbl[] = { 481 {ISD::TRUNCATE, MVT::v4i32, MVT::v4i16, 0}, 482 {ISD::TRUNCATE, MVT::v4i32, MVT::v4i8, 0}, 483 {ISD::TRUNCATE, MVT::v8i16, MVT::v8i8, 0}, 484 {ISD::TRUNCATE, MVT::v8i32, MVT::v8i16, 1}, 485 {ISD::TRUNCATE, MVT::v16i32, MVT::v16i8, 3}, 486 {ISD::TRUNCATE, MVT::v16i16, MVT::v16i8, 1}, 487 }; 488 if (SrcTy.isVector() && ST->hasMVEIntegerOps()) { 489 if (const auto *Entry = 490 ConvertCostTableLookup(MVEStoreConversionTbl, ISD, 491 SrcTy.getSimpleVT(), DstTy.getSimpleVT())) 492 return AdjustCost(Entry->Cost * ST->getMVEVectorCostFactor()); 493 } 494 495 static const TypeConversionCostTblEntry MVEFStoreConversionTbl[] = { 496 {ISD::FP_ROUND, MVT::v4f32, MVT::v4f16, 1}, 497 {ISD::FP_ROUND, MVT::v8f32, MVT::v8f16, 3}, 498 }; 499 if (SrcTy.isVector() && ST->hasMVEFloatOps()) { 500 if (const auto *Entry = 501 ConvertCostTableLookup(MVEFStoreConversionTbl, ISD, 502 SrcTy.getSimpleVT(), DstTy.getSimpleVT())) 503 return AdjustCost(Entry->Cost * ST->getMVEVectorCostFactor()); 504 } 505 } 506 507 // NEON vector operations that can extend their inputs. 508 if ((ISD == ISD::SIGN_EXTEND || ISD == ISD::ZERO_EXTEND) && 509 I && I->hasOneUse() && ST->hasNEON() && SrcTy.isVector()) { 510 static const TypeConversionCostTblEntry NEONDoubleWidthTbl[] = { 511 // vaddl 512 { ISD::ADD, MVT::v4i32, MVT::v4i16, 0 }, 513 { ISD::ADD, MVT::v8i16, MVT::v8i8, 0 }, 514 // vsubl 515 { ISD::SUB, MVT::v4i32, MVT::v4i16, 0 }, 516 { ISD::SUB, MVT::v8i16, MVT::v8i8, 0 }, 517 // vmull 518 { ISD::MUL, MVT::v4i32, MVT::v4i16, 0 }, 519 { ISD::MUL, MVT::v8i16, MVT::v8i8, 0 }, 520 // vshll 521 { ISD::SHL, MVT::v4i32, MVT::v4i16, 0 }, 522 { ISD::SHL, MVT::v8i16, MVT::v8i8, 0 }, 523 }; 524 525 auto *User = cast<Instruction>(*I->user_begin()); 526 int UserISD = TLI->InstructionOpcodeToISD(User->getOpcode()); 527 if (auto *Entry = ConvertCostTableLookup(NEONDoubleWidthTbl, UserISD, 528 DstTy.getSimpleVT(), 529 SrcTy.getSimpleVT())) { 530 return AdjustCost(Entry->Cost); 531 } 532 } 533 534 // Single to/from double precision conversions. 535 if (Src->isVectorTy() && ST->hasNEON() && 536 ((ISD == ISD::FP_ROUND && SrcTy.getScalarType() == MVT::f64 && 537 DstTy.getScalarType() == MVT::f32) || 538 (ISD == ISD::FP_EXTEND && SrcTy.getScalarType() == MVT::f32 && 539 DstTy.getScalarType() == MVT::f64))) { 540 static const CostTblEntry NEONFltDblTbl[] = { 541 // Vector fptrunc/fpext conversions. 542 {ISD::FP_ROUND, MVT::v2f64, 2}, 543 {ISD::FP_EXTEND, MVT::v2f32, 2}, 544 {ISD::FP_EXTEND, MVT::v4f32, 4}}; 545 546 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src); 547 if (const auto *Entry = CostTableLookup(NEONFltDblTbl, ISD, LT.second)) 548 return AdjustCost(LT.first * Entry->Cost); 549 } 550 551 // Some arithmetic, load and store operations have specific instructions 552 // to cast up/down their types automatically at no extra cost. 553 // TODO: Get these tables to know at least what the related operations are. 554 static const TypeConversionCostTblEntry NEONVectorConversionTbl[] = { 555 { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 1 }, 556 { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 1 }, 557 { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i32, 1 }, 558 { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i32, 1 }, 559 { ISD::TRUNCATE, MVT::v4i32, MVT::v4i64, 0 }, 560 { ISD::TRUNCATE, MVT::v4i16, MVT::v4i32, 1 }, 561 562 // The number of vmovl instructions for the extension. 563 { ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 1 }, 564 { ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 1 }, 565 { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 2 }, 566 { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 2 }, 567 { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i8, 3 }, 568 { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i8, 3 }, 569 { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i16, 2 }, 570 { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i16, 2 }, 571 { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16, 3 }, 572 { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16, 3 }, 573 { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i8, 3 }, 574 { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i8, 3 }, 575 { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i8, 7 }, 576 { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i8, 7 }, 577 { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i16, 6 }, 578 { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i16, 6 }, 579 { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 6 }, 580 { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 6 }, 581 582 // Operations that we legalize using splitting. 583 { ISD::TRUNCATE, MVT::v16i8, MVT::v16i32, 6 }, 584 { ISD::TRUNCATE, MVT::v8i8, MVT::v8i32, 3 }, 585 586 // Vector float <-> i32 conversions. 587 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 }, 588 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 }, 589 590 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i8, 3 }, 591 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i8, 3 }, 592 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i16, 2 }, 593 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i16, 2 }, 594 { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 }, 595 { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 }, 596 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i1, 3 }, 597 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i1, 3 }, 598 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i8, 3 }, 599 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i8, 3 }, 600 { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 }, 601 { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 }, 602 { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 }, 603 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 }, 604 { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i32, 2 }, 605 { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i32, 2 }, 606 { ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i16, 8 }, 607 { ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i16, 8 }, 608 { ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i32, 4 }, 609 { ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i32, 4 }, 610 611 { ISD::FP_TO_SINT, MVT::v4i32, MVT::v4f32, 1 }, 612 { ISD::FP_TO_UINT, MVT::v4i32, MVT::v4f32, 1 }, 613 { ISD::FP_TO_SINT, MVT::v4i8, MVT::v4f32, 3 }, 614 { ISD::FP_TO_UINT, MVT::v4i8, MVT::v4f32, 3 }, 615 { ISD::FP_TO_SINT, MVT::v4i16, MVT::v4f32, 2 }, 616 { ISD::FP_TO_UINT, MVT::v4i16, MVT::v4f32, 2 }, 617 618 // Vector double <-> i32 conversions. 619 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 }, 620 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 }, 621 622 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i8, 4 }, 623 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i8, 4 }, 624 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i16, 3 }, 625 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i16, 3 }, 626 { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 }, 627 { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 }, 628 629 { ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f64, 2 }, 630 { ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f64, 2 }, 631 { ISD::FP_TO_SINT, MVT::v8i16, MVT::v8f32, 4 }, 632 { ISD::FP_TO_UINT, MVT::v8i16, MVT::v8f32, 4 }, 633 { ISD::FP_TO_SINT, MVT::v16i16, MVT::v16f32, 8 }, 634 { ISD::FP_TO_UINT, MVT::v16i16, MVT::v16f32, 8 } 635 }; 636 637 if (SrcTy.isVector() && ST->hasNEON()) { 638 if (const auto *Entry = ConvertCostTableLookup(NEONVectorConversionTbl, ISD, 639 DstTy.getSimpleVT(), 640 SrcTy.getSimpleVT())) 641 return AdjustCost(Entry->Cost); 642 } 643 644 // Scalar float to integer conversions. 645 static const TypeConversionCostTblEntry NEONFloatConversionTbl[] = { 646 { ISD::FP_TO_SINT, MVT::i1, MVT::f32, 2 }, 647 { ISD::FP_TO_UINT, MVT::i1, MVT::f32, 2 }, 648 { ISD::FP_TO_SINT, MVT::i1, MVT::f64, 2 }, 649 { ISD::FP_TO_UINT, MVT::i1, MVT::f64, 2 }, 650 { ISD::FP_TO_SINT, MVT::i8, MVT::f32, 2 }, 651 { ISD::FP_TO_UINT, MVT::i8, MVT::f32, 2 }, 652 { ISD::FP_TO_SINT, MVT::i8, MVT::f64, 2 }, 653 { ISD::FP_TO_UINT, MVT::i8, MVT::f64, 2 }, 654 { ISD::FP_TO_SINT, MVT::i16, MVT::f32, 2 }, 655 { ISD::FP_TO_UINT, MVT::i16, MVT::f32, 2 }, 656 { ISD::FP_TO_SINT, MVT::i16, MVT::f64, 2 }, 657 { ISD::FP_TO_UINT, MVT::i16, MVT::f64, 2 }, 658 { ISD::FP_TO_SINT, MVT::i32, MVT::f32, 2 }, 659 { ISD::FP_TO_UINT, MVT::i32, MVT::f32, 2 }, 660 { ISD::FP_TO_SINT, MVT::i32, MVT::f64, 2 }, 661 { ISD::FP_TO_UINT, MVT::i32, MVT::f64, 2 }, 662 { ISD::FP_TO_SINT, MVT::i64, MVT::f32, 10 }, 663 { ISD::FP_TO_UINT, MVT::i64, MVT::f32, 10 }, 664 { ISD::FP_TO_SINT, MVT::i64, MVT::f64, 10 }, 665 { ISD::FP_TO_UINT, MVT::i64, MVT::f64, 10 } 666 }; 667 if (SrcTy.isFloatingPoint() && ST->hasNEON()) { 668 if (const auto *Entry = ConvertCostTableLookup(NEONFloatConversionTbl, ISD, 669 DstTy.getSimpleVT(), 670 SrcTy.getSimpleVT())) 671 return AdjustCost(Entry->Cost); 672 } 673 674 // Scalar integer to float conversions. 675 static const TypeConversionCostTblEntry NEONIntegerConversionTbl[] = { 676 { ISD::SINT_TO_FP, MVT::f32, MVT::i1, 2 }, 677 { ISD::UINT_TO_FP, MVT::f32, MVT::i1, 2 }, 678 { ISD::SINT_TO_FP, MVT::f64, MVT::i1, 2 }, 679 { ISD::UINT_TO_FP, MVT::f64, MVT::i1, 2 }, 680 { ISD::SINT_TO_FP, MVT::f32, MVT::i8, 2 }, 681 { ISD::UINT_TO_FP, MVT::f32, MVT::i8, 2 }, 682 { ISD::SINT_TO_FP, MVT::f64, MVT::i8, 2 }, 683 { ISD::UINT_TO_FP, MVT::f64, MVT::i8, 2 }, 684 { ISD::SINT_TO_FP, MVT::f32, MVT::i16, 2 }, 685 { ISD::UINT_TO_FP, MVT::f32, MVT::i16, 2 }, 686 { ISD::SINT_TO_FP, MVT::f64, MVT::i16, 2 }, 687 { ISD::UINT_TO_FP, MVT::f64, MVT::i16, 2 }, 688 { ISD::SINT_TO_FP, MVT::f32, MVT::i32, 2 }, 689 { ISD::UINT_TO_FP, MVT::f32, MVT::i32, 2 }, 690 { ISD::SINT_TO_FP, MVT::f64, MVT::i32, 2 }, 691 { ISD::UINT_TO_FP, MVT::f64, MVT::i32, 2 }, 692 { ISD::SINT_TO_FP, MVT::f32, MVT::i64, 10 }, 693 { ISD::UINT_TO_FP, MVT::f32, MVT::i64, 10 }, 694 { ISD::SINT_TO_FP, MVT::f64, MVT::i64, 10 }, 695 { ISD::UINT_TO_FP, MVT::f64, MVT::i64, 10 } 696 }; 697 698 if (SrcTy.isInteger() && ST->hasNEON()) { 699 if (const auto *Entry = ConvertCostTableLookup(NEONIntegerConversionTbl, 700 ISD, DstTy.getSimpleVT(), 701 SrcTy.getSimpleVT())) 702 return AdjustCost(Entry->Cost); 703 } 704 705 // MVE extend costs, taken from codegen tests. i8->i16 or i16->i32 is one 706 // instruction, i8->i32 is two. i64 zexts are an VAND with a constant, sext 707 // are linearised so take more. 708 static const TypeConversionCostTblEntry MVEVectorConversionTbl[] = { 709 { ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 1 }, 710 { ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 1 }, 711 { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 2 }, 712 { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 2 }, 713 { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i8, 10 }, 714 { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i8, 2 }, 715 { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 1 }, 716 { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 1 }, 717 { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i16, 10 }, 718 { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i16, 2 }, 719 { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i32, 8 }, 720 { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i32, 2 }, 721 }; 722 723 if (SrcTy.isVector() && ST->hasMVEIntegerOps()) { 724 if (const auto *Entry = ConvertCostTableLookup(MVEVectorConversionTbl, 725 ISD, DstTy.getSimpleVT(), 726 SrcTy.getSimpleVT())) 727 return AdjustCost(Entry->Cost * ST->getMVEVectorCostFactor()); 728 } 729 730 if (ISD == ISD::FP_ROUND || ISD == ISD::FP_EXTEND) { 731 // As general rule, fp converts that were not matched above are scalarized 732 // and cost 1 vcvt for each lane, so long as the instruction is available. 733 // If not it will become a series of function calls. 734 const int CallCost = getCallInstrCost(nullptr, Dst, {Src}, CostKind); 735 int Lanes = 1; 736 if (SrcTy.isFixedLengthVector()) 737 Lanes = SrcTy.getVectorNumElements(); 738 739 if (IsLegalFPType(SrcTy) && IsLegalFPType(DstTy)) 740 return Lanes; 741 else 742 return Lanes * CallCost; 743 } 744 745 // Scalar integer conversion costs. 746 static const TypeConversionCostTblEntry ARMIntegerConversionTbl[] = { 747 // i16 -> i64 requires two dependent operations. 748 { ISD::SIGN_EXTEND, MVT::i64, MVT::i16, 2 }, 749 750 // Truncates on i64 are assumed to be free. 751 { ISD::TRUNCATE, MVT::i32, MVT::i64, 0 }, 752 { ISD::TRUNCATE, MVT::i16, MVT::i64, 0 }, 753 { ISD::TRUNCATE, MVT::i8, MVT::i64, 0 }, 754 { ISD::TRUNCATE, MVT::i1, MVT::i64, 0 } 755 }; 756 757 if (SrcTy.isInteger()) { 758 if (const auto *Entry = ConvertCostTableLookup(ARMIntegerConversionTbl, ISD, 759 DstTy.getSimpleVT(), 760 SrcTy.getSimpleVT())) 761 return AdjustCost(Entry->Cost); 762 } 763 764 int BaseCost = ST->hasMVEIntegerOps() && Src->isVectorTy() 765 ? ST->getMVEVectorCostFactor() 766 : 1; 767 return AdjustCost( 768 BaseCost * BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I)); 769 } 770 771 int ARMTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy, 772 unsigned Index) { 773 // Penalize inserting into an D-subregister. We end up with a three times 774 // lower estimated throughput on swift. 775 if (ST->hasSlowLoadDSubregister() && Opcode == Instruction::InsertElement && 776 ValTy->isVectorTy() && ValTy->getScalarSizeInBits() <= 32) 777 return 3; 778 779 if (ST->hasNEON() && (Opcode == Instruction::InsertElement || 780 Opcode == Instruction::ExtractElement)) { 781 // Cross-class copies are expensive on many microarchitectures, 782 // so assume they are expensive by default. 783 if (cast<VectorType>(ValTy)->getElementType()->isIntegerTy()) 784 return 3; 785 786 // Even if it's not a cross class copy, this likely leads to mixing 787 // of NEON and VFP code and should be therefore penalized. 788 if (ValTy->isVectorTy() && 789 ValTy->getScalarSizeInBits() <= 32) 790 return std::max(BaseT::getVectorInstrCost(Opcode, ValTy, Index), 2U); 791 } 792 793 if (ST->hasMVEIntegerOps() && (Opcode == Instruction::InsertElement || 794 Opcode == Instruction::ExtractElement)) { 795 // We say MVE moves costs at least the MVEVectorCostFactor, even though 796 // they are scalar instructions. This helps prevent mixing scalar and 797 // vector, to prevent vectorising where we end up just scalarising the 798 // result anyway. 799 return std::max(BaseT::getVectorInstrCost(Opcode, ValTy, Index), 800 ST->getMVEVectorCostFactor()) * 801 cast<FixedVectorType>(ValTy)->getNumElements() / 2; 802 } 803 804 return BaseT::getVectorInstrCost(Opcode, ValTy, Index); 805 } 806 807 int ARMTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, 808 TTI::TargetCostKind CostKind, 809 const Instruction *I) { 810 int ISD = TLI->InstructionOpcodeToISD(Opcode); 811 812 // Thumb scalar code size cost for select. 813 if (CostKind == TTI::TCK_CodeSize && ISD == ISD::SELECT && 814 ST->isThumb() && !ValTy->isVectorTy()) { 815 // Assume expensive structs. 816 if (TLI->getValueType(DL, ValTy, true) == MVT::Other) 817 return TTI::TCC_Expensive; 818 819 // Select costs can vary because they: 820 // - may require one or more conditional mov (including an IT), 821 // - can't operate directly on immediates, 822 // - require live flags, which we can't copy around easily. 823 int Cost = TLI->getTypeLegalizationCost(DL, ValTy).first; 824 825 // Possible IT instruction for Thumb2, or more for Thumb1. 826 ++Cost; 827 828 // i1 values may need rematerialising by using mov immediates and/or 829 // flag setting instructions. 830 if (ValTy->isIntegerTy(1)) 831 ++Cost; 832 833 return Cost; 834 } 835 836 if (CostKind != TTI::TCK_RecipThroughput) 837 return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, CostKind, I); 838 839 // On NEON a vector select gets lowered to vbsl. 840 if (ST->hasNEON() && ValTy->isVectorTy() && ISD == ISD::SELECT) { 841 // Lowering of some vector selects is currently far from perfect. 842 static const TypeConversionCostTblEntry NEONVectorSelectTbl[] = { 843 { ISD::SELECT, MVT::v4i1, MVT::v4i64, 4*4 + 1*2 + 1 }, 844 { ISD::SELECT, MVT::v8i1, MVT::v8i64, 50 }, 845 { ISD::SELECT, MVT::v16i1, MVT::v16i64, 100 } 846 }; 847 848 EVT SelCondTy = TLI->getValueType(DL, CondTy); 849 EVT SelValTy = TLI->getValueType(DL, ValTy); 850 if (SelCondTy.isSimple() && SelValTy.isSimple()) { 851 if (const auto *Entry = ConvertCostTableLookup(NEONVectorSelectTbl, ISD, 852 SelCondTy.getSimpleVT(), 853 SelValTy.getSimpleVT())) 854 return Entry->Cost; 855 } 856 857 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy); 858 return LT.first; 859 } 860 861 int BaseCost = ST->hasMVEIntegerOps() && ValTy->isVectorTy() 862 ? ST->getMVEVectorCostFactor() 863 : 1; 864 return BaseCost * BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, CostKind, 865 I); 866 } 867 868 int ARMTTIImpl::getAddressComputationCost(Type *Ty, ScalarEvolution *SE, 869 const SCEV *Ptr) { 870 // Address computations in vectorized code with non-consecutive addresses will 871 // likely result in more instructions compared to scalar code where the 872 // computation can more often be merged into the index mode. The resulting 873 // extra micro-ops can significantly decrease throughput. 874 unsigned NumVectorInstToHideOverhead = 10; 875 int MaxMergeDistance = 64; 876 877 if (ST->hasNEON()) { 878 if (Ty->isVectorTy() && SE && 879 !BaseT::isConstantStridedAccessLessThan(SE, Ptr, MaxMergeDistance + 1)) 880 return NumVectorInstToHideOverhead; 881 882 // In many cases the address computation is not merged into the instruction 883 // addressing mode. 884 return 1; 885 } 886 return BaseT::getAddressComputationCost(Ty, SE, Ptr); 887 } 888 889 bool ARMTTIImpl::isProfitableLSRChainElement(Instruction *I) { 890 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) { 891 // If a VCTP is part of a chain, it's already profitable and shouldn't be 892 // optimized, else LSR may block tail-predication. 893 switch (II->getIntrinsicID()) { 894 case Intrinsic::arm_mve_vctp8: 895 case Intrinsic::arm_mve_vctp16: 896 case Intrinsic::arm_mve_vctp32: 897 case Intrinsic::arm_mve_vctp64: 898 return true; 899 default: 900 break; 901 } 902 } 903 return false; 904 } 905 906 bool ARMTTIImpl::isLegalMaskedLoad(Type *DataTy, Align Alignment) { 907 if (!EnableMaskedLoadStores || !ST->hasMVEIntegerOps()) 908 return false; 909 910 if (auto *VecTy = dyn_cast<FixedVectorType>(DataTy)) { 911 // Don't support v2i1 yet. 912 if (VecTy->getNumElements() == 2) 913 return false; 914 915 // We don't support extending fp types. 916 unsigned VecWidth = DataTy->getPrimitiveSizeInBits(); 917 if (VecWidth != 128 && VecTy->getElementType()->isFloatingPointTy()) 918 return false; 919 } 920 921 unsigned EltWidth = DataTy->getScalarSizeInBits(); 922 return (EltWidth == 32 && Alignment >= 4) || 923 (EltWidth == 16 && Alignment >= 2) || (EltWidth == 8); 924 } 925 926 bool ARMTTIImpl::isLegalMaskedGather(Type *Ty, Align Alignment) { 927 if (!EnableMaskedGatherScatters || !ST->hasMVEIntegerOps()) 928 return false; 929 930 // This method is called in 2 places: 931 // - from the vectorizer with a scalar type, in which case we need to get 932 // this as good as we can with the limited info we have (and rely on the cost 933 // model for the rest). 934 // - from the masked intrinsic lowering pass with the actual vector type. 935 // For MVE, we have a custom lowering pass that will already have custom 936 // legalised any gathers that we can to MVE intrinsics, and want to expand all 937 // the rest. The pass runs before the masked intrinsic lowering pass, so if we 938 // are here, we know we want to expand. 939 if (isa<VectorType>(Ty)) 940 return false; 941 942 unsigned EltWidth = Ty->getScalarSizeInBits(); 943 return ((EltWidth == 32 && Alignment >= 4) || 944 (EltWidth == 16 && Alignment >= 2) || EltWidth == 8); 945 } 946 947 int ARMTTIImpl::getMemcpyCost(const Instruction *I) { 948 const MemCpyInst *MI = dyn_cast<MemCpyInst>(I); 949 assert(MI && "MemcpyInst expected"); 950 ConstantInt *C = dyn_cast<ConstantInt>(MI->getLength()); 951 952 // To model the cost of a library call, we assume 1 for the call, and 953 // 3 for the argument setup. 954 const unsigned LibCallCost = 4; 955 956 // If 'size' is not a constant, a library call will be generated. 957 if (!C) 958 return LibCallCost; 959 960 const unsigned Size = C->getValue().getZExtValue(); 961 const Align DstAlign = *MI->getDestAlign(); 962 const Align SrcAlign = *MI->getSourceAlign(); 963 const Function *F = I->getParent()->getParent(); 964 const unsigned Limit = TLI->getMaxStoresPerMemmove(F->hasMinSize()); 965 std::vector<EVT> MemOps; 966 967 // MemOps will be poplulated with a list of data types that needs to be 968 // loaded and stored. That's why we multiply the number of elements by 2 to 969 // get the cost for this memcpy. 970 if (getTLI()->findOptimalMemOpLowering( 971 MemOps, Limit, 972 MemOp::Copy(Size, /*DstAlignCanChange*/ false, DstAlign, SrcAlign, 973 /*IsVolatile*/ true), 974 MI->getDestAddressSpace(), MI->getSourceAddressSpace(), 975 F->getAttributes())) 976 return MemOps.size() * 2; 977 978 // If we can't find an optimal memop lowering, return the default cost 979 return LibCallCost; 980 } 981 982 int ARMTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, VectorType *Tp, 983 int Index, VectorType *SubTp) { 984 if (ST->hasNEON()) { 985 if (Kind == TTI::SK_Broadcast) { 986 static const CostTblEntry NEONDupTbl[] = { 987 // VDUP handles these cases. 988 {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1}, 989 {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1}, 990 {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1}, 991 {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1}, 992 {ISD::VECTOR_SHUFFLE, MVT::v4i16, 1}, 993 {ISD::VECTOR_SHUFFLE, MVT::v8i8, 1}, 994 995 {ISD::VECTOR_SHUFFLE, MVT::v4i32, 1}, 996 {ISD::VECTOR_SHUFFLE, MVT::v4f32, 1}, 997 {ISD::VECTOR_SHUFFLE, MVT::v8i16, 1}, 998 {ISD::VECTOR_SHUFFLE, MVT::v16i8, 1}}; 999 1000 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp); 1001 1002 if (const auto *Entry = 1003 CostTableLookup(NEONDupTbl, ISD::VECTOR_SHUFFLE, LT.second)) 1004 return LT.first * Entry->Cost; 1005 } 1006 if (Kind == TTI::SK_Reverse) { 1007 static const CostTblEntry NEONShuffleTbl[] = { 1008 // Reverse shuffle cost one instruction if we are shuffling within a 1009 // double word (vrev) or two if we shuffle a quad word (vrev, vext). 1010 {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1}, 1011 {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1}, 1012 {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1}, 1013 {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1}, 1014 {ISD::VECTOR_SHUFFLE, MVT::v4i16, 1}, 1015 {ISD::VECTOR_SHUFFLE, MVT::v8i8, 1}, 1016 1017 {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2}, 1018 {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2}, 1019 {ISD::VECTOR_SHUFFLE, MVT::v8i16, 2}, 1020 {ISD::VECTOR_SHUFFLE, MVT::v16i8, 2}}; 1021 1022 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp); 1023 1024 if (const auto *Entry = 1025 CostTableLookup(NEONShuffleTbl, ISD::VECTOR_SHUFFLE, LT.second)) 1026 return LT.first * Entry->Cost; 1027 } 1028 if (Kind == TTI::SK_Select) { 1029 static const CostTblEntry NEONSelShuffleTbl[] = { 1030 // Select shuffle cost table for ARM. Cost is the number of 1031 // instructions 1032 // required to create the shuffled vector. 1033 1034 {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1}, 1035 {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1}, 1036 {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1}, 1037 {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1}, 1038 1039 {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2}, 1040 {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2}, 1041 {ISD::VECTOR_SHUFFLE, MVT::v4i16, 2}, 1042 1043 {ISD::VECTOR_SHUFFLE, MVT::v8i16, 16}, 1044 1045 {ISD::VECTOR_SHUFFLE, MVT::v16i8, 32}}; 1046 1047 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp); 1048 if (const auto *Entry = CostTableLookup(NEONSelShuffleTbl, 1049 ISD::VECTOR_SHUFFLE, LT.second)) 1050 return LT.first * Entry->Cost; 1051 } 1052 } 1053 if (ST->hasMVEIntegerOps()) { 1054 if (Kind == TTI::SK_Broadcast) { 1055 static const CostTblEntry MVEDupTbl[] = { 1056 // VDUP handles these cases. 1057 {ISD::VECTOR_SHUFFLE, MVT::v4i32, 1}, 1058 {ISD::VECTOR_SHUFFLE, MVT::v8i16, 1}, 1059 {ISD::VECTOR_SHUFFLE, MVT::v16i8, 1}, 1060 {ISD::VECTOR_SHUFFLE, MVT::v4f32, 1}, 1061 {ISD::VECTOR_SHUFFLE, MVT::v8f16, 1}}; 1062 1063 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp); 1064 1065 if (const auto *Entry = CostTableLookup(MVEDupTbl, ISD::VECTOR_SHUFFLE, 1066 LT.second)) 1067 return LT.first * Entry->Cost * ST->getMVEVectorCostFactor(); 1068 } 1069 } 1070 int BaseCost = ST->hasMVEIntegerOps() && Tp->isVectorTy() 1071 ? ST->getMVEVectorCostFactor() 1072 : 1; 1073 return BaseCost * BaseT::getShuffleCost(Kind, Tp, Index, SubTp); 1074 } 1075 1076 int ARMTTIImpl::getArithmeticInstrCost(unsigned Opcode, Type *Ty, 1077 TTI::TargetCostKind CostKind, 1078 TTI::OperandValueKind Op1Info, 1079 TTI::OperandValueKind Op2Info, 1080 TTI::OperandValueProperties Opd1PropInfo, 1081 TTI::OperandValueProperties Opd2PropInfo, 1082 ArrayRef<const Value *> Args, 1083 const Instruction *CxtI) { 1084 int ISDOpcode = TLI->InstructionOpcodeToISD(Opcode); 1085 if (ST->isThumb() && CostKind == TTI::TCK_CodeSize && Ty->isIntegerTy(1)) { 1086 // Make operations on i1 relatively expensive as this often involves 1087 // combining predicates. AND and XOR should be easier to handle with IT 1088 // blocks. 1089 switch (ISDOpcode) { 1090 default: 1091 break; 1092 case ISD::AND: 1093 case ISD::XOR: 1094 return 2; 1095 case ISD::OR: 1096 return 3; 1097 } 1098 } 1099 1100 // TODO: Handle more cost kinds. 1101 if (CostKind != TTI::TCK_RecipThroughput) 1102 return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info, 1103 Op2Info, Opd1PropInfo, 1104 Opd2PropInfo, Args, CxtI); 1105 1106 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty); 1107 1108 if (ST->hasNEON()) { 1109 const unsigned FunctionCallDivCost = 20; 1110 const unsigned ReciprocalDivCost = 10; 1111 static const CostTblEntry CostTbl[] = { 1112 // Division. 1113 // These costs are somewhat random. Choose a cost of 20 to indicate that 1114 // vectorizing devision (added function call) is going to be very expensive. 1115 // Double registers types. 1116 { ISD::SDIV, MVT::v1i64, 1 * FunctionCallDivCost}, 1117 { ISD::UDIV, MVT::v1i64, 1 * FunctionCallDivCost}, 1118 { ISD::SREM, MVT::v1i64, 1 * FunctionCallDivCost}, 1119 { ISD::UREM, MVT::v1i64, 1 * FunctionCallDivCost}, 1120 { ISD::SDIV, MVT::v2i32, 2 * FunctionCallDivCost}, 1121 { ISD::UDIV, MVT::v2i32, 2 * FunctionCallDivCost}, 1122 { ISD::SREM, MVT::v2i32, 2 * FunctionCallDivCost}, 1123 { ISD::UREM, MVT::v2i32, 2 * FunctionCallDivCost}, 1124 { ISD::SDIV, MVT::v4i16, ReciprocalDivCost}, 1125 { ISD::UDIV, MVT::v4i16, ReciprocalDivCost}, 1126 { ISD::SREM, MVT::v4i16, 4 * FunctionCallDivCost}, 1127 { ISD::UREM, MVT::v4i16, 4 * FunctionCallDivCost}, 1128 { ISD::SDIV, MVT::v8i8, ReciprocalDivCost}, 1129 { ISD::UDIV, MVT::v8i8, ReciprocalDivCost}, 1130 { ISD::SREM, MVT::v8i8, 8 * FunctionCallDivCost}, 1131 { ISD::UREM, MVT::v8i8, 8 * FunctionCallDivCost}, 1132 // Quad register types. 1133 { ISD::SDIV, MVT::v2i64, 2 * FunctionCallDivCost}, 1134 { ISD::UDIV, MVT::v2i64, 2 * FunctionCallDivCost}, 1135 { ISD::SREM, MVT::v2i64, 2 * FunctionCallDivCost}, 1136 { ISD::UREM, MVT::v2i64, 2 * FunctionCallDivCost}, 1137 { ISD::SDIV, MVT::v4i32, 4 * FunctionCallDivCost}, 1138 { ISD::UDIV, MVT::v4i32, 4 * FunctionCallDivCost}, 1139 { ISD::SREM, MVT::v4i32, 4 * FunctionCallDivCost}, 1140 { ISD::UREM, MVT::v4i32, 4 * FunctionCallDivCost}, 1141 { ISD::SDIV, MVT::v8i16, 8 * FunctionCallDivCost}, 1142 { ISD::UDIV, MVT::v8i16, 8 * FunctionCallDivCost}, 1143 { ISD::SREM, MVT::v8i16, 8 * FunctionCallDivCost}, 1144 { ISD::UREM, MVT::v8i16, 8 * FunctionCallDivCost}, 1145 { ISD::SDIV, MVT::v16i8, 16 * FunctionCallDivCost}, 1146 { ISD::UDIV, MVT::v16i8, 16 * FunctionCallDivCost}, 1147 { ISD::SREM, MVT::v16i8, 16 * FunctionCallDivCost}, 1148 { ISD::UREM, MVT::v16i8, 16 * FunctionCallDivCost}, 1149 // Multiplication. 1150 }; 1151 1152 if (const auto *Entry = CostTableLookup(CostTbl, ISDOpcode, LT.second)) 1153 return LT.first * Entry->Cost; 1154 1155 int Cost = BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info, 1156 Op2Info, 1157 Opd1PropInfo, Opd2PropInfo); 1158 1159 // This is somewhat of a hack. The problem that we are facing is that SROA 1160 // creates a sequence of shift, and, or instructions to construct values. 1161 // These sequences are recognized by the ISel and have zero-cost. Not so for 1162 // the vectorized code. Because we have support for v2i64 but not i64 those 1163 // sequences look particularly beneficial to vectorize. 1164 // To work around this we increase the cost of v2i64 operations to make them 1165 // seem less beneficial. 1166 if (LT.second == MVT::v2i64 && 1167 Op2Info == TargetTransformInfo::OK_UniformConstantValue) 1168 Cost += 4; 1169 1170 return Cost; 1171 } 1172 1173 // If this operation is a shift on arm/thumb2, it might well be folded into 1174 // the following instruction, hence having a cost of 0. 1175 auto LooksLikeAFreeShift = [&]() { 1176 if (ST->isThumb1Only() || Ty->isVectorTy()) 1177 return false; 1178 1179 if (!CxtI || !CxtI->hasOneUse() || !CxtI->isShift()) 1180 return false; 1181 if (Op2Info != TargetTransformInfo::OK_UniformConstantValue) 1182 return false; 1183 1184 // Folded into a ADC/ADD/AND/BIC/CMP/EOR/MVN/ORR/ORN/RSB/SBC/SUB 1185 switch (cast<Instruction>(CxtI->user_back())->getOpcode()) { 1186 case Instruction::Add: 1187 case Instruction::Sub: 1188 case Instruction::And: 1189 case Instruction::Xor: 1190 case Instruction::Or: 1191 case Instruction::ICmp: 1192 return true; 1193 default: 1194 return false; 1195 } 1196 }; 1197 if (LooksLikeAFreeShift()) 1198 return 0; 1199 1200 int BaseCost = ST->hasMVEIntegerOps() && Ty->isVectorTy() 1201 ? ST->getMVEVectorCostFactor() 1202 : 1; 1203 1204 // The rest of this mostly follows what is done in BaseT::getArithmeticInstrCost, 1205 // without treating floats as more expensive that scalars or increasing the 1206 // costs for custom operations. The results is also multiplied by the 1207 // MVEVectorCostFactor where appropriate. 1208 if (TLI->isOperationLegalOrCustomOrPromote(ISDOpcode, LT.second)) 1209 return LT.first * BaseCost; 1210 1211 // Else this is expand, assume that we need to scalarize this op. 1212 if (auto *VTy = dyn_cast<FixedVectorType>(Ty)) { 1213 unsigned Num = VTy->getNumElements(); 1214 unsigned Cost = getArithmeticInstrCost(Opcode, Ty->getScalarType(), 1215 CostKind); 1216 // Return the cost of multiple scalar invocation plus the cost of 1217 // inserting and extracting the values. 1218 return BaseT::getScalarizationOverhead(VTy, Args) + Num * Cost; 1219 } 1220 1221 return BaseCost; 1222 } 1223 1224 int ARMTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src, 1225 MaybeAlign Alignment, unsigned AddressSpace, 1226 TTI::TargetCostKind CostKind, 1227 const Instruction *I) { 1228 // TODO: Handle other cost kinds. 1229 if (CostKind != TTI::TCK_RecipThroughput) 1230 return 1; 1231 1232 // Type legalization can't handle structs 1233 if (TLI->getValueType(DL, Src, true) == MVT::Other) 1234 return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace, 1235 CostKind); 1236 1237 if (ST->hasNEON() && Src->isVectorTy() && 1238 (Alignment && *Alignment != Align(16)) && 1239 cast<VectorType>(Src)->getElementType()->isDoubleTy()) { 1240 // Unaligned loads/stores are extremely inefficient. 1241 // We need 4 uops for vst.1/vld.1 vs 1uop for vldr/vstr. 1242 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src); 1243 return LT.first * 4; 1244 } 1245 1246 // MVE can optimize a fpext(load(4xhalf)) using an extending integer load. 1247 // Same for stores. 1248 if (ST->hasMVEFloatOps() && isa<FixedVectorType>(Src) && I && 1249 ((Opcode == Instruction::Load && I->hasOneUse() && 1250 isa<FPExtInst>(*I->user_begin())) || 1251 (Opcode == Instruction::Store && isa<FPTruncInst>(I->getOperand(0))))) { 1252 FixedVectorType *SrcVTy = cast<FixedVectorType>(Src); 1253 Type *DstTy = 1254 Opcode == Instruction::Load 1255 ? (*I->user_begin())->getType() 1256 : cast<Instruction>(I->getOperand(0))->getOperand(0)->getType(); 1257 if (SrcVTy->getNumElements() == 4 && SrcVTy->getScalarType()->isHalfTy() && 1258 DstTy->getScalarType()->isFloatTy()) 1259 return ST->getMVEVectorCostFactor(); 1260 } 1261 1262 int BaseCost = ST->hasMVEIntegerOps() && Src->isVectorTy() 1263 ? ST->getMVEVectorCostFactor() 1264 : 1; 1265 return BaseCost * BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace, 1266 CostKind, I); 1267 } 1268 1269 int ARMTTIImpl::getInterleavedMemoryOpCost( 1270 unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices, 1271 Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, 1272 bool UseMaskForCond, bool UseMaskForGaps) { 1273 assert(Factor >= 2 && "Invalid interleave factor"); 1274 assert(isa<VectorType>(VecTy) && "Expect a vector type"); 1275 1276 // vldN/vstN doesn't support vector types of i64/f64 element. 1277 bool EltIs64Bits = DL.getTypeSizeInBits(VecTy->getScalarType()) == 64; 1278 1279 if (Factor <= TLI->getMaxSupportedInterleaveFactor() && !EltIs64Bits && 1280 !UseMaskForCond && !UseMaskForGaps) { 1281 unsigned NumElts = cast<FixedVectorType>(VecTy)->getNumElements(); 1282 auto *SubVecTy = 1283 FixedVectorType::get(VecTy->getScalarType(), NumElts / Factor); 1284 1285 // vldN/vstN only support legal vector types of size 64 or 128 in bits. 1286 // Accesses having vector types that are a multiple of 128 bits can be 1287 // matched to more than one vldN/vstN instruction. 1288 int BaseCost = ST->hasMVEIntegerOps() ? ST->getMVEVectorCostFactor() : 1; 1289 if (NumElts % Factor == 0 && 1290 TLI->isLegalInterleavedAccessType(Factor, SubVecTy, DL)) 1291 return Factor * BaseCost * TLI->getNumInterleavedAccesses(SubVecTy, DL); 1292 1293 // Some smaller than legal interleaved patterns are cheap as we can make 1294 // use of the vmovn or vrev patterns to interleave a standard load. This is 1295 // true for v4i8, v8i8 and v4i16 at least (but not for v4f16 as it is 1296 // promoted differently). The cost of 2 here is then a load and vrev or 1297 // vmovn. 1298 if (ST->hasMVEIntegerOps() && Factor == 2 && NumElts / Factor > 2 && 1299 VecTy->isIntOrIntVectorTy() && DL.getTypeSizeInBits(SubVecTy) <= 64) 1300 return 2 * BaseCost; 1301 } 1302 1303 return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices, 1304 Alignment, AddressSpace, CostKind, 1305 UseMaskForCond, UseMaskForGaps); 1306 } 1307 1308 unsigned ARMTTIImpl::getGatherScatterOpCost(unsigned Opcode, Type *DataTy, 1309 const Value *Ptr, bool VariableMask, 1310 Align Alignment, 1311 TTI::TargetCostKind CostKind, 1312 const Instruction *I) { 1313 using namespace PatternMatch; 1314 if (!ST->hasMVEIntegerOps() || !EnableMaskedGatherScatters) 1315 return BaseT::getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask, 1316 Alignment, CostKind, I); 1317 1318 assert(DataTy->isVectorTy() && "Can't do gather/scatters on scalar!"); 1319 auto *VTy = cast<FixedVectorType>(DataTy); 1320 1321 // TODO: Splitting, once we do that. 1322 1323 unsigned NumElems = VTy->getNumElements(); 1324 unsigned EltSize = VTy->getScalarSizeInBits(); 1325 std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, DataTy); 1326 1327 // For now, it is assumed that for the MVE gather instructions the loads are 1328 // all effectively serialised. This means the cost is the scalar cost 1329 // multiplied by the number of elements being loaded. This is possibly very 1330 // conservative, but even so we still end up vectorising loops because the 1331 // cost per iteration for many loops is lower than for scalar loops. 1332 unsigned VectorCost = NumElems * LT.first * ST->getMVEVectorCostFactor(); 1333 // The scalarization cost should be a lot higher. We use the number of vector 1334 // elements plus the scalarization overhead. 1335 unsigned ScalarCost = 1336 NumElems * LT.first + BaseT::getScalarizationOverhead(VTy, {}); 1337 1338 if (Alignment < EltSize / 8) 1339 return ScalarCost; 1340 1341 unsigned ExtSize = EltSize; 1342 // Check whether there's a single user that asks for an extended type 1343 if (I != nullptr) { 1344 // Dependent of the caller of this function, a gather instruction will 1345 // either have opcode Instruction::Load or be a call to the masked_gather 1346 // intrinsic 1347 if ((I->getOpcode() == Instruction::Load || 1348 match(I, m_Intrinsic<Intrinsic::masked_gather>())) && 1349 I->hasOneUse()) { 1350 const User *Us = *I->users().begin(); 1351 if (isa<ZExtInst>(Us) || isa<SExtInst>(Us)) { 1352 // only allow valid type combinations 1353 unsigned TypeSize = 1354 cast<Instruction>(Us)->getType()->getScalarSizeInBits(); 1355 if (((TypeSize == 32 && (EltSize == 8 || EltSize == 16)) || 1356 (TypeSize == 16 && EltSize == 8)) && 1357 TypeSize * NumElems == 128) { 1358 ExtSize = TypeSize; 1359 } 1360 } 1361 } 1362 // Check whether the input data needs to be truncated 1363 TruncInst *T; 1364 if ((I->getOpcode() == Instruction::Store || 1365 match(I, m_Intrinsic<Intrinsic::masked_scatter>())) && 1366 (T = dyn_cast<TruncInst>(I->getOperand(0)))) { 1367 // Only allow valid type combinations 1368 unsigned TypeSize = T->getOperand(0)->getType()->getScalarSizeInBits(); 1369 if (((EltSize == 16 && TypeSize == 32) || 1370 (EltSize == 8 && (TypeSize == 32 || TypeSize == 16))) && 1371 TypeSize * NumElems == 128) 1372 ExtSize = TypeSize; 1373 } 1374 } 1375 1376 if (ExtSize * NumElems != 128 || NumElems < 4) 1377 return ScalarCost; 1378 1379 // Any (aligned) i32 gather will not need to be scalarised. 1380 if (ExtSize == 32) 1381 return VectorCost; 1382 // For smaller types, we need to ensure that the gep's inputs are correctly 1383 // extended from a small enough value. Other sizes (including i64) are 1384 // scalarized for now. 1385 if (ExtSize != 8 && ExtSize != 16) 1386 return ScalarCost; 1387 1388 if (const auto *BC = dyn_cast<BitCastInst>(Ptr)) 1389 Ptr = BC->getOperand(0); 1390 if (const auto *GEP = dyn_cast<GetElementPtrInst>(Ptr)) { 1391 if (GEP->getNumOperands() != 2) 1392 return ScalarCost; 1393 unsigned Scale = DL.getTypeAllocSize(GEP->getResultElementType()); 1394 // Scale needs to be correct (which is only relevant for i16s). 1395 if (Scale != 1 && Scale * 8 != ExtSize) 1396 return ScalarCost; 1397 // And we need to zext (not sext) the indexes from a small enough type. 1398 if (const auto *ZExt = dyn_cast<ZExtInst>(GEP->getOperand(1))) { 1399 if (ZExt->getOperand(0)->getType()->getScalarSizeInBits() <= ExtSize) 1400 return VectorCost; 1401 } 1402 return ScalarCost; 1403 } 1404 return ScalarCost; 1405 } 1406 1407 bool ARMTTIImpl::isLoweredToCall(const Function *F) { 1408 if (!F->isIntrinsic()) 1409 BaseT::isLoweredToCall(F); 1410 1411 // Assume all Arm-specific intrinsics map to an instruction. 1412 if (F->getName().startswith("llvm.arm")) 1413 return false; 1414 1415 switch (F->getIntrinsicID()) { 1416 default: break; 1417 case Intrinsic::powi: 1418 case Intrinsic::sin: 1419 case Intrinsic::cos: 1420 case Intrinsic::pow: 1421 case Intrinsic::log: 1422 case Intrinsic::log10: 1423 case Intrinsic::log2: 1424 case Intrinsic::exp: 1425 case Intrinsic::exp2: 1426 return true; 1427 case Intrinsic::sqrt: 1428 case Intrinsic::fabs: 1429 case Intrinsic::copysign: 1430 case Intrinsic::floor: 1431 case Intrinsic::ceil: 1432 case Intrinsic::trunc: 1433 case Intrinsic::rint: 1434 case Intrinsic::nearbyint: 1435 case Intrinsic::round: 1436 case Intrinsic::canonicalize: 1437 case Intrinsic::lround: 1438 case Intrinsic::llround: 1439 case Intrinsic::lrint: 1440 case Intrinsic::llrint: 1441 if (F->getReturnType()->isDoubleTy() && !ST->hasFP64()) 1442 return true; 1443 if (F->getReturnType()->isHalfTy() && !ST->hasFullFP16()) 1444 return true; 1445 // Some operations can be handled by vector instructions and assume 1446 // unsupported vectors will be expanded into supported scalar ones. 1447 // TODO Handle scalar operations properly. 1448 return !ST->hasFPARMv8Base() && !ST->hasVFP2Base(); 1449 case Intrinsic::masked_store: 1450 case Intrinsic::masked_load: 1451 case Intrinsic::masked_gather: 1452 case Intrinsic::masked_scatter: 1453 return !ST->hasMVEIntegerOps(); 1454 case Intrinsic::sadd_with_overflow: 1455 case Intrinsic::uadd_with_overflow: 1456 case Intrinsic::ssub_with_overflow: 1457 case Intrinsic::usub_with_overflow: 1458 case Intrinsic::sadd_sat: 1459 case Intrinsic::uadd_sat: 1460 case Intrinsic::ssub_sat: 1461 case Intrinsic::usub_sat: 1462 return false; 1463 } 1464 1465 return BaseT::isLoweredToCall(F); 1466 } 1467 1468 bool ARMTTIImpl::maybeLoweredToCall(Instruction &I) { 1469 unsigned ISD = TLI->InstructionOpcodeToISD(I.getOpcode()); 1470 EVT VT = TLI->getValueType(DL, I.getType(), true); 1471 if (TLI->getOperationAction(ISD, VT) == TargetLowering::LibCall) 1472 return true; 1473 1474 // Check if an intrinsic will be lowered to a call and assume that any 1475 // other CallInst will generate a bl. 1476 if (auto *Call = dyn_cast<CallInst>(&I)) { 1477 if (isa<IntrinsicInst>(Call)) { 1478 if (const Function *F = Call->getCalledFunction()) 1479 return isLoweredToCall(F); 1480 } 1481 return true; 1482 } 1483 1484 // FPv5 provides conversions between integer, double-precision, 1485 // single-precision, and half-precision formats. 1486 switch (I.getOpcode()) { 1487 default: 1488 break; 1489 case Instruction::FPToSI: 1490 case Instruction::FPToUI: 1491 case Instruction::SIToFP: 1492 case Instruction::UIToFP: 1493 case Instruction::FPTrunc: 1494 case Instruction::FPExt: 1495 return !ST->hasFPARMv8Base(); 1496 } 1497 1498 // FIXME: Unfortunately the approach of checking the Operation Action does 1499 // not catch all cases of Legalization that use library calls. Our 1500 // Legalization step categorizes some transformations into library calls as 1501 // Custom, Expand or even Legal when doing type legalization. So for now 1502 // we have to special case for instance the SDIV of 64bit integers and the 1503 // use of floating point emulation. 1504 if (VT.isInteger() && VT.getSizeInBits() >= 64) { 1505 switch (ISD) { 1506 default: 1507 break; 1508 case ISD::SDIV: 1509 case ISD::UDIV: 1510 case ISD::SREM: 1511 case ISD::UREM: 1512 case ISD::SDIVREM: 1513 case ISD::UDIVREM: 1514 return true; 1515 } 1516 } 1517 1518 // Assume all other non-float operations are supported. 1519 if (!VT.isFloatingPoint()) 1520 return false; 1521 1522 // We'll need a library call to handle most floats when using soft. 1523 if (TLI->useSoftFloat()) { 1524 switch (I.getOpcode()) { 1525 default: 1526 return true; 1527 case Instruction::Alloca: 1528 case Instruction::Load: 1529 case Instruction::Store: 1530 case Instruction::Select: 1531 case Instruction::PHI: 1532 return false; 1533 } 1534 } 1535 1536 // We'll need a libcall to perform double precision operations on a single 1537 // precision only FPU. 1538 if (I.getType()->isDoubleTy() && !ST->hasFP64()) 1539 return true; 1540 1541 // Likewise for half precision arithmetic. 1542 if (I.getType()->isHalfTy() && !ST->hasFullFP16()) 1543 return true; 1544 1545 return false; 1546 } 1547 1548 bool ARMTTIImpl::isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE, 1549 AssumptionCache &AC, 1550 TargetLibraryInfo *LibInfo, 1551 HardwareLoopInfo &HWLoopInfo) { 1552 // Low-overhead branches are only supported in the 'low-overhead branch' 1553 // extension of v8.1-m. 1554 if (!ST->hasLOB() || DisableLowOverheadLoops) { 1555 LLVM_DEBUG(dbgs() << "ARMHWLoops: Disabled\n"); 1556 return false; 1557 } 1558 1559 if (!SE.hasLoopInvariantBackedgeTakenCount(L)) { 1560 LLVM_DEBUG(dbgs() << "ARMHWLoops: No BETC\n"); 1561 return false; 1562 } 1563 1564 const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L); 1565 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) { 1566 LLVM_DEBUG(dbgs() << "ARMHWLoops: Uncomputable BETC\n"); 1567 return false; 1568 } 1569 1570 const SCEV *TripCountSCEV = 1571 SE.getAddExpr(BackedgeTakenCount, 1572 SE.getOne(BackedgeTakenCount->getType())); 1573 1574 // We need to store the trip count in LR, a 32-bit register. 1575 if (SE.getUnsignedRangeMax(TripCountSCEV).getBitWidth() > 32) { 1576 LLVM_DEBUG(dbgs() << "ARMHWLoops: Trip count does not fit into 32bits\n"); 1577 return false; 1578 } 1579 1580 // Making a call will trash LR and clear LO_BRANCH_INFO, so there's little 1581 // point in generating a hardware loop if that's going to happen. 1582 1583 auto IsHardwareLoopIntrinsic = [](Instruction &I) { 1584 if (auto *Call = dyn_cast<IntrinsicInst>(&I)) { 1585 switch (Call->getIntrinsicID()) { 1586 default: 1587 break; 1588 case Intrinsic::set_loop_iterations: 1589 case Intrinsic::test_set_loop_iterations: 1590 case Intrinsic::loop_decrement: 1591 case Intrinsic::loop_decrement_reg: 1592 return true; 1593 } 1594 } 1595 return false; 1596 }; 1597 1598 // Scan the instructions to see if there's any that we know will turn into a 1599 // call or if this loop is already a low-overhead loop. 1600 auto ScanLoop = [&](Loop *L) { 1601 for (auto *BB : L->getBlocks()) { 1602 for (auto &I : *BB) { 1603 if (maybeLoweredToCall(I) || IsHardwareLoopIntrinsic(I)) { 1604 LLVM_DEBUG(dbgs() << "ARMHWLoops: Bad instruction: " << I << "\n"); 1605 return false; 1606 } 1607 } 1608 } 1609 return true; 1610 }; 1611 1612 // Visit inner loops. 1613 for (auto Inner : *L) 1614 if (!ScanLoop(Inner)) 1615 return false; 1616 1617 if (!ScanLoop(L)) 1618 return false; 1619 1620 // TODO: Check whether the trip count calculation is expensive. If L is the 1621 // inner loop but we know it has a low trip count, calculating that trip 1622 // count (in the parent loop) may be detrimental. 1623 1624 LLVMContext &C = L->getHeader()->getContext(); 1625 HWLoopInfo.CounterInReg = true; 1626 HWLoopInfo.IsNestingLegal = false; 1627 HWLoopInfo.PerformEntryTest = true; 1628 HWLoopInfo.CountType = Type::getInt32Ty(C); 1629 HWLoopInfo.LoopDecrement = ConstantInt::get(HWLoopInfo.CountType, 1); 1630 return true; 1631 } 1632 1633 static bool canTailPredicateInstruction(Instruction &I, int &ICmpCount) { 1634 // We don't allow icmp's, and because we only look at single block loops, 1635 // we simply count the icmps, i.e. there should only be 1 for the backedge. 1636 if (isa<ICmpInst>(&I) && ++ICmpCount > 1) 1637 return false; 1638 1639 if (isa<FCmpInst>(&I)) 1640 return false; 1641 1642 // We could allow extending/narrowing FP loads/stores, but codegen is 1643 // too inefficient so reject this for now. 1644 if (isa<FPExtInst>(&I) || isa<FPTruncInst>(&I)) 1645 return false; 1646 1647 // Extends have to be extending-loads 1648 if (isa<SExtInst>(&I) || isa<ZExtInst>(&I) ) 1649 if (!I.getOperand(0)->hasOneUse() || !isa<LoadInst>(I.getOperand(0))) 1650 return false; 1651 1652 // Truncs have to be narrowing-stores 1653 if (isa<TruncInst>(&I) ) 1654 if (!I.hasOneUse() || !isa<StoreInst>(*I.user_begin())) 1655 return false; 1656 1657 return true; 1658 } 1659 1660 // To set up a tail-predicated loop, we need to know the total number of 1661 // elements processed by that loop. Thus, we need to determine the element 1662 // size and: 1663 // 1) it should be uniform for all operations in the vector loop, so we 1664 // e.g. don't want any widening/narrowing operations. 1665 // 2) it should be smaller than i64s because we don't have vector operations 1666 // that work on i64s. 1667 // 3) we don't want elements to be reversed or shuffled, to make sure the 1668 // tail-predication masks/predicates the right lanes. 1669 // 1670 static bool canTailPredicateLoop(Loop *L, LoopInfo *LI, ScalarEvolution &SE, 1671 const DataLayout &DL, 1672 const LoopAccessInfo *LAI) { 1673 LLVM_DEBUG(dbgs() << "Tail-predication: checking allowed instructions\n"); 1674 1675 // If there are live-out values, it is probably a reduction. We can predicate 1676 // most reduction operations freely under MVE using a combination of 1677 // prefer-predicated-reduction-select and inloop reductions. We limit this to 1678 // floating point and integer reductions, but don't check for operators 1679 // specifically here. If the value ends up not being a reduction (and so the 1680 // vectorizer cannot tailfold the loop), we should fall back to standard 1681 // vectorization automatically. 1682 SmallVector< Instruction *, 8 > LiveOuts; 1683 LiveOuts = llvm::findDefsUsedOutsideOfLoop(L); 1684 bool ReductionsDisabled = 1685 EnableTailPredication == TailPredication::EnabledNoReductions || 1686 EnableTailPredication == TailPredication::ForceEnabledNoReductions; 1687 1688 for (auto *I : LiveOuts) { 1689 if (!I->getType()->isIntegerTy() && !I->getType()->isFloatTy() && 1690 !I->getType()->isHalfTy()) { 1691 LLVM_DEBUG(dbgs() << "Don't tail-predicate loop with non-integer/float " 1692 "live-out value\n"); 1693 return false; 1694 } 1695 if (ReductionsDisabled) { 1696 LLVM_DEBUG(dbgs() << "Reductions not enabled\n"); 1697 return false; 1698 } 1699 } 1700 1701 // Next, check that all instructions can be tail-predicated. 1702 PredicatedScalarEvolution PSE = LAI->getPSE(); 1703 SmallVector<Instruction *, 16> LoadStores; 1704 int ICmpCount = 0; 1705 1706 for (BasicBlock *BB : L->blocks()) { 1707 for (Instruction &I : BB->instructionsWithoutDebug()) { 1708 if (isa<PHINode>(&I)) 1709 continue; 1710 if (!canTailPredicateInstruction(I, ICmpCount)) { 1711 LLVM_DEBUG(dbgs() << "Instruction not allowed: "; I.dump()); 1712 return false; 1713 } 1714 1715 Type *T = I.getType(); 1716 if (T->isPointerTy()) 1717 T = T->getPointerElementType(); 1718 1719 if (T->getScalarSizeInBits() > 32) { 1720 LLVM_DEBUG(dbgs() << "Unsupported Type: "; T->dump()); 1721 return false; 1722 } 1723 if (isa<StoreInst>(I) || isa<LoadInst>(I)) { 1724 Value *Ptr = isa<LoadInst>(I) ? I.getOperand(0) : I.getOperand(1); 1725 int64_t NextStride = getPtrStride(PSE, Ptr, L); 1726 if (NextStride == 1) { 1727 // TODO: for now only allow consecutive strides of 1. We could support 1728 // other strides as long as it is uniform, but let's keep it simple 1729 // for now. 1730 continue; 1731 } else if (NextStride == -1 || 1732 (NextStride == 2 && MVEMaxSupportedInterleaveFactor >= 2) || 1733 (NextStride == 4 && MVEMaxSupportedInterleaveFactor >= 4)) { 1734 LLVM_DEBUG(dbgs() 1735 << "Consecutive strides of 2 found, vld2/vstr2 can't " 1736 "be tail-predicated\n."); 1737 return false; 1738 // TODO: don't tail predicate if there is a reversed load? 1739 } else if (EnableMaskedGatherScatters) { 1740 // Gather/scatters do allow loading from arbitrary strides, at 1741 // least if they are loop invariant. 1742 // TODO: Loop variant strides should in theory work, too, but 1743 // this requires further testing. 1744 const SCEV *PtrScev = 1745 replaceSymbolicStrideSCEV(PSE, llvm::ValueToValueMap(), Ptr); 1746 if (auto AR = dyn_cast<SCEVAddRecExpr>(PtrScev)) { 1747 const SCEV *Step = AR->getStepRecurrence(*PSE.getSE()); 1748 if (PSE.getSE()->isLoopInvariant(Step, L)) 1749 continue; 1750 } 1751 } 1752 LLVM_DEBUG(dbgs() << "Bad stride found, can't " 1753 "tail-predicate\n."); 1754 return false; 1755 } 1756 } 1757 } 1758 1759 LLVM_DEBUG(dbgs() << "tail-predication: all instructions allowed!\n"); 1760 return true; 1761 } 1762 1763 bool ARMTTIImpl::preferPredicateOverEpilogue(Loop *L, LoopInfo *LI, 1764 ScalarEvolution &SE, 1765 AssumptionCache &AC, 1766 TargetLibraryInfo *TLI, 1767 DominatorTree *DT, 1768 const LoopAccessInfo *LAI) { 1769 if (!EnableTailPredication) { 1770 LLVM_DEBUG(dbgs() << "Tail-predication not enabled.\n"); 1771 return false; 1772 } 1773 1774 // Creating a predicated vector loop is the first step for generating a 1775 // tail-predicated hardware loop, for which we need the MVE masked 1776 // load/stores instructions: 1777 if (!ST->hasMVEIntegerOps()) 1778 return false; 1779 1780 // For now, restrict this to single block loops. 1781 if (L->getNumBlocks() > 1) { 1782 LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: not a single block " 1783 "loop.\n"); 1784 return false; 1785 } 1786 1787 assert(L->empty() && "preferPredicateOverEpilogue: inner-loop expected"); 1788 1789 HardwareLoopInfo HWLoopInfo(L); 1790 if (!HWLoopInfo.canAnalyze(*LI)) { 1791 LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not " 1792 "analyzable.\n"); 1793 return false; 1794 } 1795 1796 // This checks if we have the low-overhead branch architecture 1797 // extension, and if we will create a hardware-loop: 1798 if (!isHardwareLoopProfitable(L, SE, AC, TLI, HWLoopInfo)) { 1799 LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not " 1800 "profitable.\n"); 1801 return false; 1802 } 1803 1804 if (!HWLoopInfo.isHardwareLoopCandidate(SE, *LI, *DT)) { 1805 LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not " 1806 "a candidate.\n"); 1807 return false; 1808 } 1809 1810 return canTailPredicateLoop(L, LI, SE, DL, LAI); 1811 } 1812 1813 bool ARMTTIImpl::emitGetActiveLaneMask() const { 1814 if (!ST->hasMVEIntegerOps() || !EnableTailPredication) 1815 return false; 1816 1817 // Intrinsic @llvm.get.active.lane.mask is supported. 1818 // It is used in the MVETailPredication pass, which requires the number of 1819 // elements processed by this vector loop to setup the tail-predicated 1820 // loop. 1821 return true; 1822 } 1823 void ARMTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE, 1824 TTI::UnrollingPreferences &UP) { 1825 // Only currently enable these preferences for M-Class cores. 1826 if (!ST->isMClass()) 1827 return BasicTTIImplBase::getUnrollingPreferences(L, SE, UP); 1828 1829 // Disable loop unrolling for Oz and Os. 1830 UP.OptSizeThreshold = 0; 1831 UP.PartialOptSizeThreshold = 0; 1832 if (L->getHeader()->getParent()->hasOptSize()) 1833 return; 1834 1835 // Only enable on Thumb-2 targets. 1836 if (!ST->isThumb2()) 1837 return; 1838 1839 SmallVector<BasicBlock*, 4> ExitingBlocks; 1840 L->getExitingBlocks(ExitingBlocks); 1841 LLVM_DEBUG(dbgs() << "Loop has:\n" 1842 << "Blocks: " << L->getNumBlocks() << "\n" 1843 << "Exit blocks: " << ExitingBlocks.size() << "\n"); 1844 1845 // Only allow another exit other than the latch. This acts as an early exit 1846 // as it mirrors the profitability calculation of the runtime unroller. 1847 if (ExitingBlocks.size() > 2) 1848 return; 1849 1850 // Limit the CFG of the loop body for targets with a branch predictor. 1851 // Allowing 4 blocks permits if-then-else diamonds in the body. 1852 if (ST->hasBranchPredictor() && L->getNumBlocks() > 4) 1853 return; 1854 1855 // Scan the loop: don't unroll loops with calls as this could prevent 1856 // inlining. 1857 unsigned Cost = 0; 1858 for (auto *BB : L->getBlocks()) { 1859 for (auto &I : *BB) { 1860 // Don't unroll vectorised loop. MVE does not benefit from it as much as 1861 // scalar code. 1862 if (I.getType()->isVectorTy()) 1863 return; 1864 1865 if (isa<CallInst>(I) || isa<InvokeInst>(I)) { 1866 if (const Function *F = cast<CallBase>(I).getCalledFunction()) { 1867 if (!isLoweredToCall(F)) 1868 continue; 1869 } 1870 return; 1871 } 1872 1873 SmallVector<const Value*, 4> Operands(I.value_op_begin(), 1874 I.value_op_end()); 1875 Cost += 1876 getUserCost(&I, Operands, TargetTransformInfo::TCK_SizeAndLatency); 1877 } 1878 } 1879 1880 LLVM_DEBUG(dbgs() << "Cost of loop: " << Cost << "\n"); 1881 1882 UP.Partial = true; 1883 UP.Runtime = true; 1884 UP.UpperBound = true; 1885 UP.UnrollRemainder = true; 1886 UP.DefaultUnrollRuntimeCount = 4; 1887 UP.UnrollAndJam = true; 1888 UP.UnrollAndJamInnerLoopThreshold = 60; 1889 1890 // Force unrolling small loops can be very useful because of the branch 1891 // taken cost of the backedge. 1892 if (Cost < 12) 1893 UP.Force = true; 1894 } 1895 1896 void ARMTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE, 1897 TTI::PeelingPreferences &PP) { 1898 BaseT::getPeelingPreferences(L, SE, PP); 1899 } 1900 1901 bool ARMTTIImpl::useReductionIntrinsic(unsigned Opcode, Type *Ty, 1902 TTI::ReductionFlags Flags) const { 1903 return ST->hasMVEIntegerOps(); 1904 } 1905 1906 bool ARMTTIImpl::preferInLoopReduction(unsigned Opcode, Type *Ty, 1907 TTI::ReductionFlags Flags) const { 1908 if (!ST->hasMVEIntegerOps()) 1909 return false; 1910 1911 unsigned ScalarBits = Ty->getScalarSizeInBits(); 1912 switch (Opcode) { 1913 case Instruction::Add: 1914 return ScalarBits <= 32; 1915 default: 1916 return false; 1917 } 1918 } 1919 1920 bool ARMTTIImpl::preferPredicatedReductionSelect( 1921 unsigned Opcode, Type *Ty, TTI::ReductionFlags Flags) const { 1922 if (!ST->hasMVEIntegerOps()) 1923 return false; 1924 return true; 1925 } 1926