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