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