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