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/IVDescriptors.h"
13 #include "llvm/Analysis/LoopInfo.h"
14 #include "llvm/Analysis/TargetTransformInfo.h"
15 #include "llvm/CodeGen/BasicTTIImpl.h"
16 #include "llvm/CodeGen/CostTable.h"
17 #include "llvm/CodeGen/TargetLowering.h"
18 #include "llvm/IR/Intrinsics.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/IR/IntrinsicsAArch64.h"
21 #include "llvm/IR/PatternMatch.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Transforms/InstCombine/InstCombiner.h"
24 #include <algorithm>
25 using namespace llvm;
26 using namespace llvm::PatternMatch;
27 
28 #define DEBUG_TYPE "aarch64tti"
29 
30 static cl::opt<bool> EnableFalkorHWPFUnrollFix("enable-falkor-hwpf-unroll-fix",
31                                                cl::init(true), cl::Hidden);
32 
33 bool AArch64TTIImpl::areInlineCompatible(const Function *Caller,
34                                          const Function *Callee) const {
35   const TargetMachine &TM = getTLI()->getTargetMachine();
36 
37   const FeatureBitset &CallerBits =
38       TM.getSubtargetImpl(*Caller)->getFeatureBits();
39   const FeatureBitset &CalleeBits =
40       TM.getSubtargetImpl(*Callee)->getFeatureBits();
41 
42   // Inline a callee if its target-features are a subset of the callers
43   // target-features.
44   return (CallerBits & CalleeBits) == CalleeBits;
45 }
46 
47 /// Calculate the cost of materializing a 64-bit value. This helper
48 /// method might only calculate a fraction of a larger immediate. Therefore it
49 /// is valid to return a cost of ZERO.
50 InstructionCost AArch64TTIImpl::getIntImmCost(int64_t Val) {
51   // Check if the immediate can be encoded within an instruction.
52   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, 64))
53     return 0;
54 
55   if (Val < 0)
56     Val = ~Val;
57 
58   // Calculate how many moves we will need to materialize this constant.
59   SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
60   AArch64_IMM::expandMOVImm(Val, 64, Insn);
61   return Insn.size();
62 }
63 
64 /// Calculate the cost of materializing the given constant.
65 InstructionCost AArch64TTIImpl::getIntImmCost(const APInt &Imm, Type *Ty,
66                                               TTI::TargetCostKind CostKind) {
67   assert(Ty->isIntegerTy());
68 
69   unsigned BitSize = Ty->getPrimitiveSizeInBits();
70   if (BitSize == 0)
71     return ~0U;
72 
73   // Sign-extend all constants to a multiple of 64-bit.
74   APInt ImmVal = Imm;
75   if (BitSize & 0x3f)
76     ImmVal = Imm.sext((BitSize + 63) & ~0x3fU);
77 
78   // Split the constant into 64-bit chunks and calculate the cost for each
79   // chunk.
80   InstructionCost Cost = 0;
81   for (unsigned ShiftVal = 0; ShiftVal < BitSize; ShiftVal += 64) {
82     APInt Tmp = ImmVal.ashr(ShiftVal).sextOrTrunc(64);
83     int64_t Val = Tmp.getSExtValue();
84     Cost += getIntImmCost(Val);
85   }
86   // We need at least one instruction to materialze the constant.
87   return std::max<InstructionCost>(1, Cost);
88 }
89 
90 InstructionCost AArch64TTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx,
91                                                   const APInt &Imm, Type *Ty,
92                                                   TTI::TargetCostKind CostKind,
93                                                   Instruction *Inst) {
94   assert(Ty->isIntegerTy());
95 
96   unsigned BitSize = Ty->getPrimitiveSizeInBits();
97   // There is no cost model for constants with a bit size of 0. Return TCC_Free
98   // here, so that constant hoisting will ignore this constant.
99   if (BitSize == 0)
100     return TTI::TCC_Free;
101 
102   unsigned ImmIdx = ~0U;
103   switch (Opcode) {
104   default:
105     return TTI::TCC_Free;
106   case Instruction::GetElementPtr:
107     // Always hoist the base address of a GetElementPtr.
108     if (Idx == 0)
109       return 2 * TTI::TCC_Basic;
110     return TTI::TCC_Free;
111   case Instruction::Store:
112     ImmIdx = 0;
113     break;
114   case Instruction::Add:
115   case Instruction::Sub:
116   case Instruction::Mul:
117   case Instruction::UDiv:
118   case Instruction::SDiv:
119   case Instruction::URem:
120   case Instruction::SRem:
121   case Instruction::And:
122   case Instruction::Or:
123   case Instruction::Xor:
124   case Instruction::ICmp:
125     ImmIdx = 1;
126     break;
127   // Always return TCC_Free for the shift value of a shift instruction.
128   case Instruction::Shl:
129   case Instruction::LShr:
130   case Instruction::AShr:
131     if (Idx == 1)
132       return TTI::TCC_Free;
133     break;
134   case Instruction::Trunc:
135   case Instruction::ZExt:
136   case Instruction::SExt:
137   case Instruction::IntToPtr:
138   case Instruction::PtrToInt:
139   case Instruction::BitCast:
140   case Instruction::PHI:
141   case Instruction::Call:
142   case Instruction::Select:
143   case Instruction::Ret:
144   case Instruction::Load:
145     break;
146   }
147 
148   if (Idx == ImmIdx) {
149     int NumConstants = (BitSize + 63) / 64;
150     InstructionCost Cost = AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
151     return (Cost <= NumConstants * TTI::TCC_Basic)
152                ? static_cast<int>(TTI::TCC_Free)
153                : Cost;
154   }
155   return AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
156 }
157 
158 InstructionCost
159 AArch64TTIImpl::getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx,
160                                     const APInt &Imm, Type *Ty,
161                                     TTI::TargetCostKind CostKind) {
162   assert(Ty->isIntegerTy());
163 
164   unsigned BitSize = Ty->getPrimitiveSizeInBits();
165   // There is no cost model for constants with a bit size of 0. Return TCC_Free
166   // here, so that constant hoisting will ignore this constant.
167   if (BitSize == 0)
168     return TTI::TCC_Free;
169 
170   // Most (all?) AArch64 intrinsics do not support folding immediates into the
171   // selected instruction, so we compute the materialization cost for the
172   // immediate directly.
173   if (IID >= Intrinsic::aarch64_addg && IID <= Intrinsic::aarch64_udiv)
174     return AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
175 
176   switch (IID) {
177   default:
178     return TTI::TCC_Free;
179   case Intrinsic::sadd_with_overflow:
180   case Intrinsic::uadd_with_overflow:
181   case Intrinsic::ssub_with_overflow:
182   case Intrinsic::usub_with_overflow:
183   case Intrinsic::smul_with_overflow:
184   case Intrinsic::umul_with_overflow:
185     if (Idx == 1) {
186       int NumConstants = (BitSize + 63) / 64;
187       InstructionCost Cost = AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
188       return (Cost <= NumConstants * TTI::TCC_Basic)
189                  ? static_cast<int>(TTI::TCC_Free)
190                  : Cost;
191     }
192     break;
193   case Intrinsic::experimental_stackmap:
194     if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
195       return TTI::TCC_Free;
196     break;
197   case Intrinsic::experimental_patchpoint_void:
198   case Intrinsic::experimental_patchpoint_i64:
199     if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
200       return TTI::TCC_Free;
201     break;
202   case Intrinsic::experimental_gc_statepoint:
203     if ((Idx < 5) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
204       return TTI::TCC_Free;
205     break;
206   }
207   return AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
208 }
209 
210 TargetTransformInfo::PopcntSupportKind
211 AArch64TTIImpl::getPopcntSupport(unsigned TyWidth) {
212   assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
213   if (TyWidth == 32 || TyWidth == 64)
214     return TTI::PSK_FastHardware;
215   // TODO: AArch64TargetLowering::LowerCTPOP() supports 128bit popcount.
216   return TTI::PSK_Software;
217 }
218 
219 InstructionCost
220 AArch64TTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
221                                       TTI::TargetCostKind CostKind) {
222   auto *RetTy = ICA.getReturnType();
223   switch (ICA.getID()) {
224   case Intrinsic::umin:
225   case Intrinsic::umax:
226   case Intrinsic::smin:
227   case Intrinsic::smax: {
228     static const auto ValidMinMaxTys = {MVT::v8i8,  MVT::v16i8, MVT::v4i16,
229                                         MVT::v8i16, MVT::v2i32, MVT::v4i32};
230     auto LT = TLI->getTypeLegalizationCost(DL, RetTy);
231     // v2i64 types get converted to cmp+bif hence the cost of 2
232     if (LT.second == MVT::v2i64)
233       return LT.first * 2;
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   case Intrinsic::bitreverse: {
277     static const CostTblEntry BitreverseTbl[] = {
278         {Intrinsic::bitreverse, MVT::i32, 1},
279         {Intrinsic::bitreverse, MVT::i64, 1},
280         {Intrinsic::bitreverse, MVT::v8i8, 1},
281         {Intrinsic::bitreverse, MVT::v16i8, 1},
282         {Intrinsic::bitreverse, MVT::v4i16, 2},
283         {Intrinsic::bitreverse, MVT::v8i16, 2},
284         {Intrinsic::bitreverse, MVT::v2i32, 2},
285         {Intrinsic::bitreverse, MVT::v4i32, 2},
286         {Intrinsic::bitreverse, MVT::v1i64, 2},
287         {Intrinsic::bitreverse, MVT::v2i64, 2},
288     };
289     const auto LegalisationCost = TLI->getTypeLegalizationCost(DL, RetTy);
290     const auto *Entry =
291         CostTableLookup(BitreverseTbl, ICA.getID(), LegalisationCost.second);
292     if (Entry) {
293       // Cost Model is using the legal type(i32) that i8 and i16 will be
294       // converted to +1 so that we match the actual lowering cost
295       if (TLI->getValueType(DL, RetTy, true) == MVT::i8 ||
296           TLI->getValueType(DL, RetTy, true) == MVT::i16)
297         return LegalisationCost.first * Entry->Cost + 1;
298 
299       return LegalisationCost.first * Entry->Cost;
300     }
301     break;
302   }
303   case Intrinsic::ctpop: {
304     static const CostTblEntry CtpopCostTbl[] = {
305         {ISD::CTPOP, MVT::v2i64, 4},
306         {ISD::CTPOP, MVT::v4i32, 3},
307         {ISD::CTPOP, MVT::v8i16, 2},
308         {ISD::CTPOP, MVT::v16i8, 1},
309         {ISD::CTPOP, MVT::i64,   4},
310         {ISD::CTPOP, MVT::v2i32, 3},
311         {ISD::CTPOP, MVT::v4i16, 2},
312         {ISD::CTPOP, MVT::v8i8,  1},
313         {ISD::CTPOP, MVT::i32,   5},
314     };
315     auto LT = TLI->getTypeLegalizationCost(DL, RetTy);
316     MVT MTy = LT.second;
317     if (const auto *Entry = CostTableLookup(CtpopCostTbl, ISD::CTPOP, MTy)) {
318       // Extra cost of +1 when illegal vector types are legalized by promoting
319       // the integer type.
320       int ExtraCost = MTy.isVector() && MTy.getScalarSizeInBits() !=
321                                             RetTy->getScalarSizeInBits()
322                           ? 1
323                           : 0;
324       return LT.first * Entry->Cost + ExtraCost;
325     }
326     break;
327   }
328   default:
329     break;
330   }
331   return BaseT::getIntrinsicInstrCost(ICA, CostKind);
332 }
333 
334 /// The function will remove redundant reinterprets casting in the presence
335 /// of the control flow
336 static Optional<Instruction *> processPhiNode(InstCombiner &IC,
337                                               IntrinsicInst &II) {
338   SmallVector<Instruction *, 32> Worklist;
339   auto RequiredType = II.getType();
340 
341   auto *PN = dyn_cast<PHINode>(II.getArgOperand(0));
342   assert(PN && "Expected Phi Node!");
343 
344   // Don't create a new Phi unless we can remove the old one.
345   if (!PN->hasOneUse())
346     return None;
347 
348   for (Value *IncValPhi : PN->incoming_values()) {
349     auto *Reinterpret = dyn_cast<IntrinsicInst>(IncValPhi);
350     if (!Reinterpret ||
351         Reinterpret->getIntrinsicID() !=
352             Intrinsic::aarch64_sve_convert_to_svbool ||
353         RequiredType != Reinterpret->getArgOperand(0)->getType())
354       return None;
355   }
356 
357   // Create the new Phi
358   LLVMContext &Ctx = PN->getContext();
359   IRBuilder<> Builder(Ctx);
360   Builder.SetInsertPoint(PN);
361   PHINode *NPN = Builder.CreatePHI(RequiredType, PN->getNumIncomingValues());
362   Worklist.push_back(PN);
363 
364   for (unsigned I = 0; I < PN->getNumIncomingValues(); I++) {
365     auto *Reinterpret = cast<Instruction>(PN->getIncomingValue(I));
366     NPN->addIncoming(Reinterpret->getOperand(0), PN->getIncomingBlock(I));
367     Worklist.push_back(Reinterpret);
368   }
369 
370   // Cleanup Phi Node and reinterprets
371   return IC.replaceInstUsesWith(II, NPN);
372 }
373 
374 static Optional<Instruction *> instCombineConvertFromSVBool(InstCombiner &IC,
375                                                             IntrinsicInst &II) {
376   // If the reinterpret instruction operand is a PHI Node
377   if (isa<PHINode>(II.getArgOperand(0)))
378     return processPhiNode(IC, II);
379 
380   SmallVector<Instruction *, 32> CandidatesForRemoval;
381   Value *Cursor = II.getOperand(0), *EarliestReplacement = nullptr;
382 
383   const auto *IVTy = cast<VectorType>(II.getType());
384 
385   // Walk the chain of conversions.
386   while (Cursor) {
387     // If the type of the cursor has fewer lanes than the final result, zeroing
388     // must take place, which breaks the equivalence chain.
389     const auto *CursorVTy = cast<VectorType>(Cursor->getType());
390     if (CursorVTy->getElementCount().getKnownMinValue() <
391         IVTy->getElementCount().getKnownMinValue())
392       break;
393 
394     // If the cursor has the same type as I, it is a viable replacement.
395     if (Cursor->getType() == IVTy)
396       EarliestReplacement = Cursor;
397 
398     auto *IntrinsicCursor = dyn_cast<IntrinsicInst>(Cursor);
399 
400     // If this is not an SVE conversion intrinsic, this is the end of the chain.
401     if (!IntrinsicCursor || !(IntrinsicCursor->getIntrinsicID() ==
402                                   Intrinsic::aarch64_sve_convert_to_svbool ||
403                               IntrinsicCursor->getIntrinsicID() ==
404                                   Intrinsic::aarch64_sve_convert_from_svbool))
405       break;
406 
407     CandidatesForRemoval.insert(CandidatesForRemoval.begin(), IntrinsicCursor);
408     Cursor = IntrinsicCursor->getOperand(0);
409   }
410 
411   // If no viable replacement in the conversion chain was found, there is
412   // nothing to do.
413   if (!EarliestReplacement)
414     return None;
415 
416   return IC.replaceInstUsesWith(II, EarliestReplacement);
417 }
418 
419 static Optional<Instruction *> instCombineSVEDup(InstCombiner &IC,
420                                                  IntrinsicInst &II) {
421   IntrinsicInst *Pg = dyn_cast<IntrinsicInst>(II.getArgOperand(1));
422   if (!Pg)
423     return None;
424 
425   if (Pg->getIntrinsicID() != Intrinsic::aarch64_sve_ptrue)
426     return None;
427 
428   const auto PTruePattern =
429       cast<ConstantInt>(Pg->getOperand(0))->getZExtValue();
430   if (PTruePattern != AArch64SVEPredPattern::vl1)
431     return None;
432 
433   // The intrinsic is inserting into lane zero so use an insert instead.
434   auto *IdxTy = Type::getInt64Ty(II.getContext());
435   auto *Insert = InsertElementInst::Create(
436       II.getArgOperand(0), II.getArgOperand(2), ConstantInt::get(IdxTy, 0));
437   Insert->insertBefore(&II);
438   Insert->takeName(&II);
439 
440   return IC.replaceInstUsesWith(II, Insert);
441 }
442 
443 static Optional<Instruction *> instCombineSVEDupX(InstCombiner &IC,
444                                                   IntrinsicInst &II) {
445   // Replace DupX with a regular IR splat.
446   IRBuilder<> Builder(II.getContext());
447   Builder.SetInsertPoint(&II);
448   auto *RetTy = cast<ScalableVectorType>(II.getType());
449   Value *Splat =
450       Builder.CreateVectorSplat(RetTy->getElementCount(), II.getArgOperand(0));
451   Splat->takeName(&II);
452   return IC.replaceInstUsesWith(II, Splat);
453 }
454 
455 static Optional<Instruction *> instCombineSVECmpNE(InstCombiner &IC,
456                                                    IntrinsicInst &II) {
457   LLVMContext &Ctx = II.getContext();
458   IRBuilder<> Builder(Ctx);
459   Builder.SetInsertPoint(&II);
460 
461   // Check that the predicate is all active
462   auto *Pg = dyn_cast<IntrinsicInst>(II.getArgOperand(0));
463   if (!Pg || Pg->getIntrinsicID() != Intrinsic::aarch64_sve_ptrue)
464     return None;
465 
466   const auto PTruePattern =
467       cast<ConstantInt>(Pg->getOperand(0))->getZExtValue();
468   if (PTruePattern != AArch64SVEPredPattern::all)
469     return None;
470 
471   // Check that we have a compare of zero..
472   auto *SplatValue =
473       dyn_cast_or_null<ConstantInt>(getSplatValue(II.getArgOperand(2)));
474   if (!SplatValue || !SplatValue->isZero())
475     return None;
476 
477   // ..against a dupq
478   auto *DupQLane = dyn_cast<IntrinsicInst>(II.getArgOperand(1));
479   if (!DupQLane ||
480       DupQLane->getIntrinsicID() != Intrinsic::aarch64_sve_dupq_lane)
481     return None;
482 
483   // Where the dupq is a lane 0 replicate of a vector insert
484   if (!cast<ConstantInt>(DupQLane->getArgOperand(1))->isZero())
485     return None;
486 
487   auto *VecIns = dyn_cast<IntrinsicInst>(DupQLane->getArgOperand(0));
488   if (!VecIns ||
489       VecIns->getIntrinsicID() != Intrinsic::experimental_vector_insert)
490     return None;
491 
492   // Where the vector insert is a fixed constant vector insert into undef at
493   // index zero
494   if (!isa<UndefValue>(VecIns->getArgOperand(0)))
495     return None;
496 
497   if (!cast<ConstantInt>(VecIns->getArgOperand(2))->isZero())
498     return None;
499 
500   auto *ConstVec = dyn_cast<Constant>(VecIns->getArgOperand(1));
501   if (!ConstVec)
502     return None;
503 
504   auto *VecTy = dyn_cast<FixedVectorType>(ConstVec->getType());
505   auto *OutTy = dyn_cast<ScalableVectorType>(II.getType());
506   if (!VecTy || !OutTy || VecTy->getNumElements() != OutTy->getMinNumElements())
507     return None;
508 
509   unsigned NumElts = VecTy->getNumElements();
510   unsigned PredicateBits = 0;
511 
512   // Expand intrinsic operands to a 16-bit byte level predicate
513   for (unsigned I = 0; I < NumElts; ++I) {
514     auto *Arg = dyn_cast<ConstantInt>(ConstVec->getAggregateElement(I));
515     if (!Arg)
516       return None;
517     if (!Arg->isZero())
518       PredicateBits |= 1 << (I * (16 / NumElts));
519   }
520 
521   // If all bits are zero bail early with an empty predicate
522   if (PredicateBits == 0) {
523     auto *PFalse = Constant::getNullValue(II.getType());
524     PFalse->takeName(&II);
525     return IC.replaceInstUsesWith(II, PFalse);
526   }
527 
528   // Calculate largest predicate type used (where byte predicate is largest)
529   unsigned Mask = 8;
530   for (unsigned I = 0; I < 16; ++I)
531     if ((PredicateBits & (1 << I)) != 0)
532       Mask |= (I % 8);
533 
534   unsigned PredSize = Mask & -Mask;
535   auto *PredType = ScalableVectorType::get(
536       Type::getInt1Ty(Ctx), AArch64::SVEBitsPerBlock / (PredSize * 8));
537 
538   // Ensure all relevant bits are set
539   for (unsigned I = 0; I < 16; I += PredSize)
540     if ((PredicateBits & (1 << I)) == 0)
541       return None;
542 
543   auto *PTruePat =
544       ConstantInt::get(Type::getInt32Ty(Ctx), AArch64SVEPredPattern::all);
545   auto *PTrue = Builder.CreateIntrinsic(Intrinsic::aarch64_sve_ptrue,
546                                         {PredType}, {PTruePat});
547   auto *ConvertToSVBool = Builder.CreateIntrinsic(
548       Intrinsic::aarch64_sve_convert_to_svbool, {PredType}, {PTrue});
549   auto *ConvertFromSVBool =
550       Builder.CreateIntrinsic(Intrinsic::aarch64_sve_convert_from_svbool,
551                               {II.getType()}, {ConvertToSVBool});
552 
553   ConvertFromSVBool->takeName(&II);
554   return IC.replaceInstUsesWith(II, ConvertFromSVBool);
555 }
556 
557 static Optional<Instruction *> instCombineSVELast(InstCombiner &IC,
558                                                   IntrinsicInst &II) {
559   IRBuilder<> Builder(II.getContext());
560   Builder.SetInsertPoint(&II);
561   Value *Pg = II.getArgOperand(0);
562   Value *Vec = II.getArgOperand(1);
563   auto IntrinsicID = II.getIntrinsicID();
564   bool IsAfter = IntrinsicID == Intrinsic::aarch64_sve_lasta;
565 
566   // lastX(splat(X)) --> X
567   if (auto *SplatVal = getSplatValue(Vec))
568     return IC.replaceInstUsesWith(II, SplatVal);
569 
570   // If x and/or y is a splat value then:
571   // lastX (binop (x, y)) --> binop(lastX(x), lastX(y))
572   Value *LHS, *RHS;
573   if (match(Vec, m_OneUse(m_BinOp(m_Value(LHS), m_Value(RHS))))) {
574     if (isSplatValue(LHS) || isSplatValue(RHS)) {
575       auto *OldBinOp = cast<BinaryOperator>(Vec);
576       auto OpC = OldBinOp->getOpcode();
577       auto *NewLHS =
578           Builder.CreateIntrinsic(IntrinsicID, {Vec->getType()}, {Pg, LHS});
579       auto *NewRHS =
580           Builder.CreateIntrinsic(IntrinsicID, {Vec->getType()}, {Pg, RHS});
581       auto *NewBinOp = BinaryOperator::CreateWithCopiedFlags(
582           OpC, NewLHS, NewRHS, OldBinOp, OldBinOp->getName(), &II);
583       return IC.replaceInstUsesWith(II, NewBinOp);
584     }
585   }
586 
587   auto *C = dyn_cast<Constant>(Pg);
588   if (IsAfter && C && C->isNullValue()) {
589     // The intrinsic is extracting lane 0 so use an extract instead.
590     auto *IdxTy = Type::getInt64Ty(II.getContext());
591     auto *Extract = ExtractElementInst::Create(Vec, ConstantInt::get(IdxTy, 0));
592     Extract->insertBefore(&II);
593     Extract->takeName(&II);
594     return IC.replaceInstUsesWith(II, Extract);
595   }
596 
597   auto *IntrPG = dyn_cast<IntrinsicInst>(Pg);
598   if (!IntrPG)
599     return None;
600 
601   if (IntrPG->getIntrinsicID() != Intrinsic::aarch64_sve_ptrue)
602     return None;
603 
604   const auto PTruePattern =
605       cast<ConstantInt>(IntrPG->getOperand(0))->getZExtValue();
606 
607   // Can the intrinsic's predicate be converted to a known constant index?
608   unsigned MinNumElts = getNumElementsFromSVEPredPattern(PTruePattern);
609   if (!MinNumElts)
610     return None;
611 
612   unsigned Idx = MinNumElts - 1;
613   // Increment the index if extracting the element after the last active
614   // predicate element.
615   if (IsAfter)
616     ++Idx;
617 
618   // Ignore extracts whose index is larger than the known minimum vector
619   // length. NOTE: This is an artificial constraint where we prefer to
620   // maintain what the user asked for until an alternative is proven faster.
621   auto *PgVTy = cast<ScalableVectorType>(Pg->getType());
622   if (Idx >= PgVTy->getMinNumElements())
623     return None;
624 
625   // The intrinsic is extracting a fixed lane so use an extract instead.
626   auto *IdxTy = Type::getInt64Ty(II.getContext());
627   auto *Extract = ExtractElementInst::Create(Vec, ConstantInt::get(IdxTy, Idx));
628   Extract->insertBefore(&II);
629   Extract->takeName(&II);
630   return IC.replaceInstUsesWith(II, Extract);
631 }
632 
633 static Optional<Instruction *> instCombineRDFFR(InstCombiner &IC,
634                                                 IntrinsicInst &II) {
635   LLVMContext &Ctx = II.getContext();
636   IRBuilder<> Builder(Ctx);
637   Builder.SetInsertPoint(&II);
638   // Replace rdffr with predicated rdffr.z intrinsic, so that optimizePTestInstr
639   // can work with RDFFR_PP for ptest elimination.
640   auto *AllPat =
641       ConstantInt::get(Type::getInt32Ty(Ctx), AArch64SVEPredPattern::all);
642   auto *PTrue = Builder.CreateIntrinsic(Intrinsic::aarch64_sve_ptrue,
643                                         {II.getType()}, {AllPat});
644   auto *RDFFR =
645       Builder.CreateIntrinsic(Intrinsic::aarch64_sve_rdffr_z, {}, {PTrue});
646   RDFFR->takeName(&II);
647   return IC.replaceInstUsesWith(II, RDFFR);
648 }
649 
650 static Optional<Instruction *>
651 instCombineSVECntElts(InstCombiner &IC, IntrinsicInst &II, unsigned NumElts) {
652   const auto Pattern = cast<ConstantInt>(II.getArgOperand(0))->getZExtValue();
653 
654   if (Pattern == AArch64SVEPredPattern::all) {
655     LLVMContext &Ctx = II.getContext();
656     IRBuilder<> Builder(Ctx);
657     Builder.SetInsertPoint(&II);
658 
659     Constant *StepVal = ConstantInt::get(II.getType(), NumElts);
660     auto *VScale = Builder.CreateVScale(StepVal);
661     VScale->takeName(&II);
662     return IC.replaceInstUsesWith(II, VScale);
663   }
664 
665   unsigned MinNumElts = getNumElementsFromSVEPredPattern(Pattern);
666 
667   return MinNumElts && NumElts >= MinNumElts
668              ? Optional<Instruction *>(IC.replaceInstUsesWith(
669                    II, ConstantInt::get(II.getType(), MinNumElts)))
670              : None;
671 }
672 
673 static Optional<Instruction *> instCombineSVEPTest(InstCombiner &IC,
674                                                    IntrinsicInst &II) {
675   IntrinsicInst *Op1 = dyn_cast<IntrinsicInst>(II.getArgOperand(0));
676   IntrinsicInst *Op2 = dyn_cast<IntrinsicInst>(II.getArgOperand(1));
677 
678   if (Op1 && Op2 &&
679       Op1->getIntrinsicID() == Intrinsic::aarch64_sve_convert_to_svbool &&
680       Op2->getIntrinsicID() == Intrinsic::aarch64_sve_convert_to_svbool &&
681       Op1->getArgOperand(0)->getType() == Op2->getArgOperand(0)->getType()) {
682 
683     IRBuilder<> Builder(II.getContext());
684     Builder.SetInsertPoint(&II);
685 
686     Value *Ops[] = {Op1->getArgOperand(0), Op2->getArgOperand(0)};
687     Type *Tys[] = {Op1->getArgOperand(0)->getType()};
688 
689     auto *PTest = Builder.CreateIntrinsic(II.getIntrinsicID(), Tys, Ops);
690 
691     PTest->takeName(&II);
692     return IC.replaceInstUsesWith(II, PTest);
693   }
694 
695   return None;
696 }
697 
698 static Instruction::BinaryOps intrinsicIDToBinOpCode(unsigned Intrinsic) {
699   switch (Intrinsic) {
700   case Intrinsic::aarch64_sve_fmul:
701     return Instruction::BinaryOps::FMul;
702   case Intrinsic::aarch64_sve_fadd:
703     return Instruction::BinaryOps::FAdd;
704   case Intrinsic::aarch64_sve_fsub:
705     return Instruction::BinaryOps::FSub;
706   default:
707     return Instruction::BinaryOpsEnd;
708   }
709 }
710 
711 static Optional<Instruction *> instCombineSVEVectorBinOp(InstCombiner &IC,
712                                                          IntrinsicInst &II) {
713   auto *OpPredicate = II.getOperand(0);
714   auto BinOpCode = intrinsicIDToBinOpCode(II.getIntrinsicID());
715   if (BinOpCode == Instruction::BinaryOpsEnd ||
716       !match(OpPredicate, m_Intrinsic<Intrinsic::aarch64_sve_ptrue>(
717                               m_ConstantInt<AArch64SVEPredPattern::all>())))
718     return None;
719   IRBuilder<> Builder(II.getContext());
720   Builder.SetInsertPoint(&II);
721   Builder.setFastMathFlags(II.getFastMathFlags());
722   auto BinOp =
723       Builder.CreateBinOp(BinOpCode, II.getOperand(1), II.getOperand(2));
724   return IC.replaceInstUsesWith(II, BinOp);
725 }
726 
727 static Optional<Instruction *> instCombineSVEVectorMul(InstCombiner &IC,
728                                                        IntrinsicInst &II) {
729   auto *OpPredicate = II.getOperand(0);
730   auto *OpMultiplicand = II.getOperand(1);
731   auto *OpMultiplier = II.getOperand(2);
732 
733   IRBuilder<> Builder(II.getContext());
734   Builder.SetInsertPoint(&II);
735 
736   // Return true if a given instruction is a unit splat value, false otherwise.
737   auto IsUnitSplat = [](auto *I) {
738     auto *SplatValue = getSplatValue(I);
739     if (!SplatValue)
740       return false;
741     return match(SplatValue, m_FPOne()) || match(SplatValue, m_One());
742   };
743 
744   // Return true if a given instruction is an aarch64_sve_dup intrinsic call
745   // with a unit splat value, false otherwise.
746   auto IsUnitDup = [](auto *I) {
747     auto *IntrI = dyn_cast<IntrinsicInst>(I);
748     if (!IntrI || IntrI->getIntrinsicID() != Intrinsic::aarch64_sve_dup)
749       return false;
750 
751     auto *SplatValue = IntrI->getOperand(2);
752     return match(SplatValue, m_FPOne()) || match(SplatValue, m_One());
753   };
754 
755   // The OpMultiplier variable should always point to the dup (if any), so
756   // swap if necessary.
757   if (IsUnitDup(OpMultiplicand) || IsUnitSplat(OpMultiplicand))
758     std::swap(OpMultiplier, OpMultiplicand);
759 
760   if (IsUnitSplat(OpMultiplier)) {
761     // [f]mul pg (dupx 1) %n => %n
762     OpMultiplicand->takeName(&II);
763     return IC.replaceInstUsesWith(II, OpMultiplicand);
764   } else if (IsUnitDup(OpMultiplier)) {
765     // [f]mul pg (dup pg 1) %n => %n
766     auto *DupInst = cast<IntrinsicInst>(OpMultiplier);
767     auto *DupPg = DupInst->getOperand(1);
768     // TODO: this is naive. The optimization is still valid if DupPg
769     // 'encompasses' OpPredicate, not only if they're the same predicate.
770     if (OpPredicate == DupPg) {
771       OpMultiplicand->takeName(&II);
772       return IC.replaceInstUsesWith(II, OpMultiplicand);
773     }
774   }
775 
776   return instCombineSVEVectorBinOp(IC, II);
777 }
778 
779 static Optional<Instruction *> instCombineSVEUnpack(InstCombiner &IC,
780                                                     IntrinsicInst &II) {
781   IRBuilder<> Builder(II.getContext());
782   Builder.SetInsertPoint(&II);
783   Value *UnpackArg = II.getArgOperand(0);
784   auto *RetTy = cast<ScalableVectorType>(II.getType());
785   bool IsSigned = II.getIntrinsicID() == Intrinsic::aarch64_sve_sunpkhi ||
786                   II.getIntrinsicID() == Intrinsic::aarch64_sve_sunpklo;
787 
788   // Hi = uunpkhi(splat(X)) --> Hi = splat(extend(X))
789   // Lo = uunpklo(splat(X)) --> Lo = splat(extend(X))
790   if (auto *ScalarArg = getSplatValue(UnpackArg)) {
791     ScalarArg =
792         Builder.CreateIntCast(ScalarArg, RetTy->getScalarType(), IsSigned);
793     Value *NewVal =
794         Builder.CreateVectorSplat(RetTy->getElementCount(), ScalarArg);
795     NewVal->takeName(&II);
796     return IC.replaceInstUsesWith(II, NewVal);
797   }
798 
799   return None;
800 }
801 static Optional<Instruction *> instCombineSVETBL(InstCombiner &IC,
802                                                  IntrinsicInst &II) {
803   auto *OpVal = II.getOperand(0);
804   auto *OpIndices = II.getOperand(1);
805   VectorType *VTy = cast<VectorType>(II.getType());
806 
807   // Check whether OpIndices is a constant splat value < minimal element count
808   // of result.
809   auto *SplatValue = dyn_cast_or_null<ConstantInt>(getSplatValue(OpIndices));
810   if (!SplatValue ||
811       SplatValue->getValue().uge(VTy->getElementCount().getKnownMinValue()))
812     return None;
813 
814   // Convert sve_tbl(OpVal sve_dup_x(SplatValue)) to
815   // splat_vector(extractelement(OpVal, SplatValue)) for further optimization.
816   IRBuilder<> Builder(II.getContext());
817   Builder.SetInsertPoint(&II);
818   auto *Extract = Builder.CreateExtractElement(OpVal, SplatValue);
819   auto *VectorSplat =
820       Builder.CreateVectorSplat(VTy->getElementCount(), Extract);
821 
822   VectorSplat->takeName(&II);
823   return IC.replaceInstUsesWith(II, VectorSplat);
824 }
825 
826 static Optional<Instruction *> instCombineSVETupleGet(InstCombiner &IC,
827                                                       IntrinsicInst &II) {
828   // Try to remove sequences of tuple get/set.
829   Value *SetTuple, *SetIndex, *SetValue;
830   auto *GetTuple = II.getArgOperand(0);
831   auto *GetIndex = II.getArgOperand(1);
832   // Check that we have tuple_get(GetTuple, GetIndex) where GetTuple is a
833   // call to tuple_set i.e. tuple_set(SetTuple, SetIndex, SetValue).
834   // Make sure that the types of the current intrinsic and SetValue match
835   // in order to safely remove the sequence.
836   if (!match(GetTuple,
837              m_Intrinsic<Intrinsic::aarch64_sve_tuple_set>(
838                  m_Value(SetTuple), m_Value(SetIndex), m_Value(SetValue))) ||
839       SetValue->getType() != II.getType())
840     return None;
841   // Case where we get the same index right after setting it.
842   // tuple_get(tuple_set(SetTuple, SetIndex, SetValue), GetIndex) --> SetValue
843   if (GetIndex == SetIndex)
844     return IC.replaceInstUsesWith(II, SetValue);
845   // If we are getting a different index than what was set in the tuple_set
846   // intrinsic. We can just set the input tuple to the one up in the chain.
847   // tuple_get(tuple_set(SetTuple, SetIndex, SetValue), GetIndex)
848   // --> tuple_get(SetTuple, GetIndex)
849   return IC.replaceOperand(II, 0, SetTuple);
850 }
851 
852 static Optional<Instruction *> instCombineSVEZip(InstCombiner &IC,
853                                                  IntrinsicInst &II) {
854   // zip1(uzp1(A, B), uzp2(A, B)) --> A
855   // zip2(uzp1(A, B), uzp2(A, B)) --> B
856   Value *A, *B;
857   if (match(II.getArgOperand(0),
858             m_Intrinsic<Intrinsic::aarch64_sve_uzp1>(m_Value(A), m_Value(B))) &&
859       match(II.getArgOperand(1), m_Intrinsic<Intrinsic::aarch64_sve_uzp2>(
860                                      m_Specific(A), m_Specific(B))))
861     return IC.replaceInstUsesWith(
862         II, (II.getIntrinsicID() == Intrinsic::aarch64_sve_zip1 ? A : B));
863 
864   return None;
865 }
866 
867 static Optional<Instruction *> instCombineLD1GatherIndex(InstCombiner &IC,
868                                                          IntrinsicInst &II) {
869   Value *Mask = II.getOperand(0);
870   Value *BasePtr = II.getOperand(1);
871   Value *Index = II.getOperand(2);
872   Type *Ty = II.getType();
873   Type *BasePtrTy = BasePtr->getType();
874   Value *PassThru = ConstantAggregateZero::get(Ty);
875 
876   // Contiguous gather => masked load.
877   // (sve.ld1.gather.index Mask BasePtr (sve.index IndexBase 1))
878   // => (masked.load (gep BasePtr IndexBase) Align Mask zeroinitializer)
879   Value *IndexBase;
880   if (match(Index, m_Intrinsic<Intrinsic::aarch64_sve_index>(
881                        m_Value(IndexBase), m_SpecificInt(1)))) {
882     IRBuilder<> Builder(II.getContext());
883     Builder.SetInsertPoint(&II);
884 
885     Align Alignment =
886         BasePtr->getPointerAlignment(II.getModule()->getDataLayout());
887 
888     Type *VecPtrTy = PointerType::getUnqual(Ty);
889     Value *Ptr = Builder.CreateGEP(BasePtrTy->getPointerElementType(), BasePtr,
890                                    IndexBase);
891     Ptr = Builder.CreateBitCast(Ptr, VecPtrTy);
892     CallInst *MaskedLoad =
893         Builder.CreateMaskedLoad(Ty, Ptr, Alignment, Mask, PassThru);
894     MaskedLoad->takeName(&II);
895     return IC.replaceInstUsesWith(II, MaskedLoad);
896   }
897 
898   return None;
899 }
900 
901 static Optional<Instruction *> instCombineST1ScatterIndex(InstCombiner &IC,
902                                                           IntrinsicInst &II) {
903   Value *Val = II.getOperand(0);
904   Value *Mask = II.getOperand(1);
905   Value *BasePtr = II.getOperand(2);
906   Value *Index = II.getOperand(3);
907   Type *Ty = Val->getType();
908   Type *BasePtrTy = BasePtr->getType();
909 
910   // Contiguous scatter => masked store.
911   // (sve.ld1.scatter.index Value Mask BasePtr (sve.index IndexBase 1))
912   // => (masked.store Value (gep BasePtr IndexBase) Align Mask)
913   Value *IndexBase;
914   if (match(Index, m_Intrinsic<Intrinsic::aarch64_sve_index>(
915                        m_Value(IndexBase), m_SpecificInt(1)))) {
916     IRBuilder<> Builder(II.getContext());
917     Builder.SetInsertPoint(&II);
918 
919     Align Alignment =
920         BasePtr->getPointerAlignment(II.getModule()->getDataLayout());
921 
922     Value *Ptr = Builder.CreateGEP(BasePtrTy->getPointerElementType(), BasePtr,
923                                    IndexBase);
924     Type *VecPtrTy = PointerType::getUnqual(Ty);
925     Ptr = Builder.CreateBitCast(Ptr, VecPtrTy);
926 
927     (void)Builder.CreateMaskedStore(Val, Ptr, Alignment, Mask);
928 
929     return IC.eraseInstFromFunction(II);
930   }
931 
932   return None;
933 }
934 
935 Optional<Instruction *>
936 AArch64TTIImpl::instCombineIntrinsic(InstCombiner &IC,
937                                      IntrinsicInst &II) const {
938   Intrinsic::ID IID = II.getIntrinsicID();
939   switch (IID) {
940   default:
941     break;
942   case Intrinsic::aarch64_sve_convert_from_svbool:
943     return instCombineConvertFromSVBool(IC, II);
944   case Intrinsic::aarch64_sve_dup:
945     return instCombineSVEDup(IC, II);
946   case Intrinsic::aarch64_sve_dup_x:
947     return instCombineSVEDupX(IC, II);
948   case Intrinsic::aarch64_sve_cmpne:
949   case Intrinsic::aarch64_sve_cmpne_wide:
950     return instCombineSVECmpNE(IC, II);
951   case Intrinsic::aarch64_sve_rdffr:
952     return instCombineRDFFR(IC, II);
953   case Intrinsic::aarch64_sve_lasta:
954   case Intrinsic::aarch64_sve_lastb:
955     return instCombineSVELast(IC, II);
956   case Intrinsic::aarch64_sve_cntd:
957     return instCombineSVECntElts(IC, II, 2);
958   case Intrinsic::aarch64_sve_cntw:
959     return instCombineSVECntElts(IC, II, 4);
960   case Intrinsic::aarch64_sve_cnth:
961     return instCombineSVECntElts(IC, II, 8);
962   case Intrinsic::aarch64_sve_cntb:
963     return instCombineSVECntElts(IC, II, 16);
964   case Intrinsic::aarch64_sve_ptest_any:
965   case Intrinsic::aarch64_sve_ptest_first:
966   case Intrinsic::aarch64_sve_ptest_last:
967     return instCombineSVEPTest(IC, II);
968   case Intrinsic::aarch64_sve_mul:
969   case Intrinsic::aarch64_sve_fmul:
970     return instCombineSVEVectorMul(IC, II);
971   case Intrinsic::aarch64_sve_fadd:
972   case Intrinsic::aarch64_sve_fsub:
973     return instCombineSVEVectorBinOp(IC, II);
974   case Intrinsic::aarch64_sve_tbl:
975     return instCombineSVETBL(IC, II);
976   case Intrinsic::aarch64_sve_uunpkhi:
977   case Intrinsic::aarch64_sve_uunpklo:
978   case Intrinsic::aarch64_sve_sunpkhi:
979   case Intrinsic::aarch64_sve_sunpklo:
980     return instCombineSVEUnpack(IC, II);
981   case Intrinsic::aarch64_sve_tuple_get:
982     return instCombineSVETupleGet(IC, II);
983   case Intrinsic::aarch64_sve_zip1:
984   case Intrinsic::aarch64_sve_zip2:
985     return instCombineSVEZip(IC, II);
986   case Intrinsic::aarch64_sve_ld1_gather_index:
987     return instCombineLD1GatherIndex(IC, II);
988   case Intrinsic::aarch64_sve_st1_scatter_index:
989     return instCombineST1ScatterIndex(IC, II);
990   }
991 
992   return None;
993 }
994 
995 bool AArch64TTIImpl::isWideningInstruction(Type *DstTy, unsigned Opcode,
996                                            ArrayRef<const Value *> Args) {
997 
998   // A helper that returns a vector type from the given type. The number of
999   // elements in type Ty determine the vector width.
1000   auto toVectorTy = [&](Type *ArgTy) {
1001     return VectorType::get(ArgTy->getScalarType(),
1002                            cast<VectorType>(DstTy)->getElementCount());
1003   };
1004 
1005   // Exit early if DstTy is not a vector type whose elements are at least
1006   // 16-bits wide.
1007   if (!DstTy->isVectorTy() || DstTy->getScalarSizeInBits() < 16)
1008     return false;
1009 
1010   // Determine if the operation has a widening variant. We consider both the
1011   // "long" (e.g., usubl) and "wide" (e.g., usubw) versions of the
1012   // instructions.
1013   //
1014   // TODO: Add additional widening operations (e.g., mul, shl, etc.) once we
1015   //       verify that their extending operands are eliminated during code
1016   //       generation.
1017   switch (Opcode) {
1018   case Instruction::Add: // UADDL(2), SADDL(2), UADDW(2), SADDW(2).
1019   case Instruction::Sub: // USUBL(2), SSUBL(2), USUBW(2), SSUBW(2).
1020     break;
1021   default:
1022     return false;
1023   }
1024 
1025   // To be a widening instruction (either the "wide" or "long" versions), the
1026   // second operand must be a sign- or zero extend having a single user. We
1027   // only consider extends having a single user because they may otherwise not
1028   // be eliminated.
1029   if (Args.size() != 2 ||
1030       (!isa<SExtInst>(Args[1]) && !isa<ZExtInst>(Args[1])) ||
1031       !Args[1]->hasOneUse())
1032     return false;
1033   auto *Extend = cast<CastInst>(Args[1]);
1034 
1035   // Legalize the destination type and ensure it can be used in a widening
1036   // operation.
1037   auto DstTyL = TLI->getTypeLegalizationCost(DL, DstTy);
1038   unsigned DstElTySize = DstTyL.second.getScalarSizeInBits();
1039   if (!DstTyL.second.isVector() || DstElTySize != DstTy->getScalarSizeInBits())
1040     return false;
1041 
1042   // Legalize the source type and ensure it can be used in a widening
1043   // operation.
1044   auto *SrcTy = toVectorTy(Extend->getSrcTy());
1045   auto SrcTyL = TLI->getTypeLegalizationCost(DL, SrcTy);
1046   unsigned SrcElTySize = SrcTyL.second.getScalarSizeInBits();
1047   if (!SrcTyL.second.isVector() || SrcElTySize != SrcTy->getScalarSizeInBits())
1048     return false;
1049 
1050   // Get the total number of vector elements in the legalized types.
1051   InstructionCost NumDstEls =
1052       DstTyL.first * DstTyL.second.getVectorMinNumElements();
1053   InstructionCost NumSrcEls =
1054       SrcTyL.first * SrcTyL.second.getVectorMinNumElements();
1055 
1056   // Return true if the legalized types have the same number of vector elements
1057   // and the destination element type size is twice that of the source type.
1058   return NumDstEls == NumSrcEls && 2 * SrcElTySize == DstElTySize;
1059 }
1060 
1061 InstructionCost AArch64TTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst,
1062                                                  Type *Src,
1063                                                  TTI::CastContextHint CCH,
1064                                                  TTI::TargetCostKind CostKind,
1065                                                  const Instruction *I) {
1066   int ISD = TLI->InstructionOpcodeToISD(Opcode);
1067   assert(ISD && "Invalid opcode");
1068 
1069   // If the cast is observable, and it is used by a widening instruction (e.g.,
1070   // uaddl, saddw, etc.), it may be free.
1071   if (I && I->hasOneUse()) {
1072     auto *SingleUser = cast<Instruction>(*I->user_begin());
1073     SmallVector<const Value *, 4> Operands(SingleUser->operand_values());
1074     if (isWideningInstruction(Dst, SingleUser->getOpcode(), Operands)) {
1075       // If the cast is the second operand, it is free. We will generate either
1076       // a "wide" or "long" version of the widening instruction.
1077       if (I == SingleUser->getOperand(1))
1078         return 0;
1079       // If the cast is not the second operand, it will be free if it looks the
1080       // same as the second operand. In this case, we will generate a "long"
1081       // version of the widening instruction.
1082       if (auto *Cast = dyn_cast<CastInst>(SingleUser->getOperand(1)))
1083         if (I->getOpcode() == unsigned(Cast->getOpcode()) &&
1084             cast<CastInst>(I)->getSrcTy() == Cast->getSrcTy())
1085           return 0;
1086     }
1087   }
1088 
1089   // TODO: Allow non-throughput costs that aren't binary.
1090   auto AdjustCost = [&CostKind](InstructionCost Cost) -> InstructionCost {
1091     if (CostKind != TTI::TCK_RecipThroughput)
1092       return Cost == 0 ? 0 : 1;
1093     return Cost;
1094   };
1095 
1096   EVT SrcTy = TLI->getValueType(DL, Src);
1097   EVT DstTy = TLI->getValueType(DL, Dst);
1098 
1099   if (!SrcTy.isSimple() || !DstTy.isSimple())
1100     return AdjustCost(
1101         BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I));
1102 
1103   static const TypeConversionCostTblEntry
1104   ConversionTbl[] = {
1105     { ISD::TRUNCATE, MVT::v4i16, MVT::v4i32,  1 },
1106     { ISD::TRUNCATE, MVT::v4i32, MVT::v4i64,  0 },
1107     { ISD::TRUNCATE, MVT::v8i8,  MVT::v8i32,  3 },
1108     { ISD::TRUNCATE, MVT::v16i8, MVT::v16i32, 6 },
1109 
1110     // Truncations on nxvmiN
1111     { ISD::TRUNCATE, MVT::nxv2i1, MVT::nxv2i16, 1 },
1112     { ISD::TRUNCATE, MVT::nxv2i1, MVT::nxv2i32, 1 },
1113     { ISD::TRUNCATE, MVT::nxv2i1, MVT::nxv2i64, 1 },
1114     { ISD::TRUNCATE, MVT::nxv4i1, MVT::nxv4i16, 1 },
1115     { ISD::TRUNCATE, MVT::nxv4i1, MVT::nxv4i32, 1 },
1116     { ISD::TRUNCATE, MVT::nxv4i1, MVT::nxv4i64, 2 },
1117     { ISD::TRUNCATE, MVT::nxv8i1, MVT::nxv8i16, 1 },
1118     { ISD::TRUNCATE, MVT::nxv8i1, MVT::nxv8i32, 3 },
1119     { ISD::TRUNCATE, MVT::nxv8i1, MVT::nxv8i64, 5 },
1120     { ISD::TRUNCATE, MVT::nxv16i1, MVT::nxv16i8, 1 },
1121     { ISD::TRUNCATE, MVT::nxv2i16, MVT::nxv2i32, 1 },
1122     { ISD::TRUNCATE, MVT::nxv2i32, MVT::nxv2i64, 1 },
1123     { ISD::TRUNCATE, MVT::nxv4i16, MVT::nxv4i32, 1 },
1124     { ISD::TRUNCATE, MVT::nxv4i32, MVT::nxv4i64, 2 },
1125     { ISD::TRUNCATE, MVT::nxv8i16, MVT::nxv8i32, 3 },
1126     { ISD::TRUNCATE, MVT::nxv8i32, MVT::nxv8i64, 6 },
1127 
1128     // The number of shll instructions for the extension.
1129     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i16, 3 },
1130     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i16, 3 },
1131     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i32, 2 },
1132     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i32, 2 },
1133     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i8,  3 },
1134     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i8,  3 },
1135     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i16, 2 },
1136     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i16, 2 },
1137     { ISD::SIGN_EXTEND, MVT::v8i64,  MVT::v8i8,  7 },
1138     { ISD::ZERO_EXTEND, MVT::v8i64,  MVT::v8i8,  7 },
1139     { ISD::SIGN_EXTEND, MVT::v8i64,  MVT::v8i16, 6 },
1140     { ISD::ZERO_EXTEND, MVT::v8i64,  MVT::v8i16, 6 },
1141     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 2 },
1142     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 2 },
1143     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
1144     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
1145 
1146     // LowerVectorINT_TO_FP:
1147     { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 },
1148     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
1149     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i64, 1 },
1150     { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 },
1151     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
1152     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i64, 1 },
1153 
1154     // Complex: to v2f32
1155     { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i8,  3 },
1156     { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i16, 3 },
1157     { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i64, 2 },
1158     { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i8,  3 },
1159     { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i16, 3 },
1160     { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i64, 2 },
1161 
1162     // Complex: to v4f32
1163     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i8,  4 },
1164     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 },
1165     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i8,  3 },
1166     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 },
1167 
1168     // Complex: to v8f32
1169     { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i8,  10 },
1170     { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 },
1171     { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i8,  10 },
1172     { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 },
1173 
1174     // Complex: to v16f32
1175     { ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i8, 21 },
1176     { ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i8, 21 },
1177 
1178     // Complex: to v2f64
1179     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i8,  4 },
1180     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i16, 4 },
1181     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
1182     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i8,  4 },
1183     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i16, 4 },
1184     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
1185 
1186 
1187     // LowerVectorFP_TO_INT
1188     { ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f32, 1 },
1189     { ISD::FP_TO_SINT, MVT::v4i32, MVT::v4f32, 1 },
1190     { ISD::FP_TO_SINT, MVT::v2i64, MVT::v2f64, 1 },
1191     { ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f32, 1 },
1192     { ISD::FP_TO_UINT, MVT::v4i32, MVT::v4f32, 1 },
1193     { ISD::FP_TO_UINT, MVT::v2i64, MVT::v2f64, 1 },
1194 
1195     // Complex, from v2f32: legal type is v2i32 (no cost) or v2i64 (1 ext).
1196     { ISD::FP_TO_SINT, MVT::v2i64, MVT::v2f32, 2 },
1197     { ISD::FP_TO_SINT, MVT::v2i16, MVT::v2f32, 1 },
1198     { ISD::FP_TO_SINT, MVT::v2i8,  MVT::v2f32, 1 },
1199     { ISD::FP_TO_UINT, MVT::v2i64, MVT::v2f32, 2 },
1200     { ISD::FP_TO_UINT, MVT::v2i16, MVT::v2f32, 1 },
1201     { ISD::FP_TO_UINT, MVT::v2i8,  MVT::v2f32, 1 },
1202 
1203     // Complex, from v4f32: legal type is v4i16, 1 narrowing => ~2
1204     { ISD::FP_TO_SINT, MVT::v4i16, MVT::v4f32, 2 },
1205     { ISD::FP_TO_SINT, MVT::v4i8,  MVT::v4f32, 2 },
1206     { ISD::FP_TO_UINT, MVT::v4i16, MVT::v4f32, 2 },
1207     { ISD::FP_TO_UINT, MVT::v4i8,  MVT::v4f32, 2 },
1208 
1209     // Complex, from nxv2f32.
1210     { ISD::FP_TO_SINT, MVT::nxv2i64, MVT::nxv2f32, 1 },
1211     { ISD::FP_TO_SINT, MVT::nxv2i32, MVT::nxv2f32, 1 },
1212     { ISD::FP_TO_SINT, MVT::nxv2i16, MVT::nxv2f32, 1 },
1213     { ISD::FP_TO_SINT, MVT::nxv2i8,  MVT::nxv2f32, 1 },
1214     { ISD::FP_TO_UINT, MVT::nxv2i64, MVT::nxv2f32, 1 },
1215     { ISD::FP_TO_UINT, MVT::nxv2i32, MVT::nxv2f32, 1 },
1216     { ISD::FP_TO_UINT, MVT::nxv2i16, MVT::nxv2f32, 1 },
1217     { ISD::FP_TO_UINT, MVT::nxv2i8,  MVT::nxv2f32, 1 },
1218 
1219     // Complex, from v2f64: legal type is v2i32, 1 narrowing => ~2.
1220     { ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f64, 2 },
1221     { ISD::FP_TO_SINT, MVT::v2i16, MVT::v2f64, 2 },
1222     { ISD::FP_TO_SINT, MVT::v2i8,  MVT::v2f64, 2 },
1223     { ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f64, 2 },
1224     { ISD::FP_TO_UINT, MVT::v2i16, MVT::v2f64, 2 },
1225     { ISD::FP_TO_UINT, MVT::v2i8,  MVT::v2f64, 2 },
1226 
1227     // Complex, from nxv2f64.
1228     { ISD::FP_TO_SINT, MVT::nxv2i64, MVT::nxv2f64, 1 },
1229     { ISD::FP_TO_SINT, MVT::nxv2i32, MVT::nxv2f64, 1 },
1230     { ISD::FP_TO_SINT, MVT::nxv2i16, MVT::nxv2f64, 1 },
1231     { ISD::FP_TO_SINT, MVT::nxv2i8,  MVT::nxv2f64, 1 },
1232     { ISD::FP_TO_UINT, MVT::nxv2i64, MVT::nxv2f64, 1 },
1233     { ISD::FP_TO_UINT, MVT::nxv2i32, MVT::nxv2f64, 1 },
1234     { ISD::FP_TO_UINT, MVT::nxv2i16, MVT::nxv2f64, 1 },
1235     { ISD::FP_TO_UINT, MVT::nxv2i8,  MVT::nxv2f64, 1 },
1236 
1237     // Complex, from nxv4f32.
1238     { ISD::FP_TO_SINT, MVT::nxv4i64, MVT::nxv4f32, 4 },
1239     { ISD::FP_TO_SINT, MVT::nxv4i32, MVT::nxv4f32, 1 },
1240     { ISD::FP_TO_SINT, MVT::nxv4i16, MVT::nxv4f32, 1 },
1241     { ISD::FP_TO_SINT, MVT::nxv4i8,  MVT::nxv4f32, 1 },
1242     { ISD::FP_TO_UINT, MVT::nxv4i64, MVT::nxv4f32, 4 },
1243     { ISD::FP_TO_UINT, MVT::nxv4i32, MVT::nxv4f32, 1 },
1244     { ISD::FP_TO_UINT, MVT::nxv4i16, MVT::nxv4f32, 1 },
1245     { ISD::FP_TO_UINT, MVT::nxv4i8,  MVT::nxv4f32, 1 },
1246 
1247     // Complex, from nxv8f64. Illegal -> illegal conversions not required.
1248     { ISD::FP_TO_SINT, MVT::nxv8i16, MVT::nxv8f64, 7 },
1249     { ISD::FP_TO_SINT, MVT::nxv8i8,  MVT::nxv8f64, 7 },
1250     { ISD::FP_TO_UINT, MVT::nxv8i16, MVT::nxv8f64, 7 },
1251     { ISD::FP_TO_UINT, MVT::nxv8i8,  MVT::nxv8f64, 7 },
1252 
1253     // Complex, from nxv4f64. Illegal -> illegal conversions not required.
1254     { ISD::FP_TO_SINT, MVT::nxv4i32, MVT::nxv4f64, 3 },
1255     { ISD::FP_TO_SINT, MVT::nxv4i16, MVT::nxv4f64, 3 },
1256     { ISD::FP_TO_SINT, MVT::nxv4i8,  MVT::nxv4f64, 3 },
1257     { ISD::FP_TO_UINT, MVT::nxv4i32, MVT::nxv4f64, 3 },
1258     { ISD::FP_TO_UINT, MVT::nxv4i16, MVT::nxv4f64, 3 },
1259     { ISD::FP_TO_UINT, MVT::nxv4i8,  MVT::nxv4f64, 3 },
1260 
1261     // Complex, from nxv8f32. Illegal -> illegal conversions not required.
1262     { ISD::FP_TO_SINT, MVT::nxv8i16, MVT::nxv8f32, 3 },
1263     { ISD::FP_TO_SINT, MVT::nxv8i8,  MVT::nxv8f32, 3 },
1264     { ISD::FP_TO_UINT, MVT::nxv8i16, MVT::nxv8f32, 3 },
1265     { ISD::FP_TO_UINT, MVT::nxv8i8,  MVT::nxv8f32, 3 },
1266 
1267     // Complex, from nxv8f16.
1268     { ISD::FP_TO_SINT, MVT::nxv8i64, MVT::nxv8f16, 10 },
1269     { ISD::FP_TO_SINT, MVT::nxv8i32, MVT::nxv8f16, 4 },
1270     { ISD::FP_TO_SINT, MVT::nxv8i16, MVT::nxv8f16, 1 },
1271     { ISD::FP_TO_SINT, MVT::nxv8i8,  MVT::nxv8f16, 1 },
1272     { ISD::FP_TO_UINT, MVT::nxv8i64, MVT::nxv8f16, 10 },
1273     { ISD::FP_TO_UINT, MVT::nxv8i32, MVT::nxv8f16, 4 },
1274     { ISD::FP_TO_UINT, MVT::nxv8i16, MVT::nxv8f16, 1 },
1275     { ISD::FP_TO_UINT, MVT::nxv8i8,  MVT::nxv8f16, 1 },
1276 
1277     // Complex, from nxv4f16.
1278     { ISD::FP_TO_SINT, MVT::nxv4i64, MVT::nxv4f16, 4 },
1279     { ISD::FP_TO_SINT, MVT::nxv4i32, MVT::nxv4f16, 1 },
1280     { ISD::FP_TO_SINT, MVT::nxv4i16, MVT::nxv4f16, 1 },
1281     { ISD::FP_TO_SINT, MVT::nxv4i8,  MVT::nxv4f16, 1 },
1282     { ISD::FP_TO_UINT, MVT::nxv4i64, MVT::nxv4f16, 4 },
1283     { ISD::FP_TO_UINT, MVT::nxv4i32, MVT::nxv4f16, 1 },
1284     { ISD::FP_TO_UINT, MVT::nxv4i16, MVT::nxv4f16, 1 },
1285     { ISD::FP_TO_UINT, MVT::nxv4i8,  MVT::nxv4f16, 1 },
1286 
1287     // Complex, from nxv2f16.
1288     { ISD::FP_TO_SINT, MVT::nxv2i64, MVT::nxv2f16, 1 },
1289     { ISD::FP_TO_SINT, MVT::nxv2i32, MVT::nxv2f16, 1 },
1290     { ISD::FP_TO_SINT, MVT::nxv2i16, MVT::nxv2f16, 1 },
1291     { ISD::FP_TO_SINT, MVT::nxv2i8,  MVT::nxv2f16, 1 },
1292     { ISD::FP_TO_UINT, MVT::nxv2i64, MVT::nxv2f16, 1 },
1293     { ISD::FP_TO_UINT, MVT::nxv2i32, MVT::nxv2f16, 1 },
1294     { ISD::FP_TO_UINT, MVT::nxv2i16, MVT::nxv2f16, 1 },
1295     { ISD::FP_TO_UINT, MVT::nxv2i8,  MVT::nxv2f16, 1 },
1296 
1297     // Truncate from nxvmf32 to nxvmf16.
1298     { ISD::FP_ROUND, MVT::nxv2f16, MVT::nxv2f32, 1 },
1299     { ISD::FP_ROUND, MVT::nxv4f16, MVT::nxv4f32, 1 },
1300     { ISD::FP_ROUND, MVT::nxv8f16, MVT::nxv8f32, 3 },
1301 
1302     // Truncate from nxvmf64 to nxvmf16.
1303     { ISD::FP_ROUND, MVT::nxv2f16, MVT::nxv2f64, 1 },
1304     { ISD::FP_ROUND, MVT::nxv4f16, MVT::nxv4f64, 3 },
1305     { ISD::FP_ROUND, MVT::nxv8f16, MVT::nxv8f64, 7 },
1306 
1307     // Truncate from nxvmf64 to nxvmf32.
1308     { ISD::FP_ROUND, MVT::nxv2f32, MVT::nxv2f64, 1 },
1309     { ISD::FP_ROUND, MVT::nxv4f32, MVT::nxv4f64, 3 },
1310     { ISD::FP_ROUND, MVT::nxv8f32, MVT::nxv8f64, 6 },
1311 
1312     // Extend from nxvmf16 to nxvmf32.
1313     { ISD::FP_EXTEND, MVT::nxv2f32, MVT::nxv2f16, 1},
1314     { ISD::FP_EXTEND, MVT::nxv4f32, MVT::nxv4f16, 1},
1315     { ISD::FP_EXTEND, MVT::nxv8f32, MVT::nxv8f16, 2},
1316 
1317     // Extend from nxvmf16 to nxvmf64.
1318     { ISD::FP_EXTEND, MVT::nxv2f64, MVT::nxv2f16, 1},
1319     { ISD::FP_EXTEND, MVT::nxv4f64, MVT::nxv4f16, 2},
1320     { ISD::FP_EXTEND, MVT::nxv8f64, MVT::nxv8f16, 4},
1321 
1322     // Extend from nxvmf32 to nxvmf64.
1323     { ISD::FP_EXTEND, MVT::nxv2f64, MVT::nxv2f32, 1},
1324     { ISD::FP_EXTEND, MVT::nxv4f64, MVT::nxv4f32, 2},
1325     { ISD::FP_EXTEND, MVT::nxv8f64, MVT::nxv8f32, 6},
1326 
1327   };
1328 
1329   if (const auto *Entry = ConvertCostTableLookup(ConversionTbl, ISD,
1330                                                  DstTy.getSimpleVT(),
1331                                                  SrcTy.getSimpleVT()))
1332     return AdjustCost(Entry->Cost);
1333 
1334   return AdjustCost(
1335       BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I));
1336 }
1337 
1338 InstructionCost AArch64TTIImpl::getExtractWithExtendCost(unsigned Opcode,
1339                                                          Type *Dst,
1340                                                          VectorType *VecTy,
1341                                                          unsigned Index) {
1342 
1343   // Make sure we were given a valid extend opcode.
1344   assert((Opcode == Instruction::SExt || Opcode == Instruction::ZExt) &&
1345          "Invalid opcode");
1346 
1347   // We are extending an element we extract from a vector, so the source type
1348   // of the extend is the element type of the vector.
1349   auto *Src = VecTy->getElementType();
1350 
1351   // Sign- and zero-extends are for integer types only.
1352   assert(isa<IntegerType>(Dst) && isa<IntegerType>(Src) && "Invalid type");
1353 
1354   // Get the cost for the extract. We compute the cost (if any) for the extend
1355   // below.
1356   InstructionCost Cost =
1357       getVectorInstrCost(Instruction::ExtractElement, VecTy, Index);
1358 
1359   // Legalize the types.
1360   auto VecLT = TLI->getTypeLegalizationCost(DL, VecTy);
1361   auto DstVT = TLI->getValueType(DL, Dst);
1362   auto SrcVT = TLI->getValueType(DL, Src);
1363   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
1364 
1365   // If the resulting type is still a vector and the destination type is legal,
1366   // we may get the extension for free. If not, get the default cost for the
1367   // extend.
1368   if (!VecLT.second.isVector() || !TLI->isTypeLegal(DstVT))
1369     return Cost + getCastInstrCost(Opcode, Dst, Src, TTI::CastContextHint::None,
1370                                    CostKind);
1371 
1372   // The destination type should be larger than the element type. If not, get
1373   // the default cost for the extend.
1374   if (DstVT.getFixedSizeInBits() < SrcVT.getFixedSizeInBits())
1375     return Cost + getCastInstrCost(Opcode, Dst, Src, TTI::CastContextHint::None,
1376                                    CostKind);
1377 
1378   switch (Opcode) {
1379   default:
1380     llvm_unreachable("Opcode should be either SExt or ZExt");
1381 
1382   // For sign-extends, we only need a smov, which performs the extension
1383   // automatically.
1384   case Instruction::SExt:
1385     return Cost;
1386 
1387   // For zero-extends, the extend is performed automatically by a umov unless
1388   // the destination type is i64 and the element type is i8 or i16.
1389   case Instruction::ZExt:
1390     if (DstVT.getSizeInBits() != 64u || SrcVT.getSizeInBits() == 32u)
1391       return Cost;
1392   }
1393 
1394   // If we are unable to perform the extend for free, get the default cost.
1395   return Cost + getCastInstrCost(Opcode, Dst, Src, TTI::CastContextHint::None,
1396                                  CostKind);
1397 }
1398 
1399 InstructionCost AArch64TTIImpl::getCFInstrCost(unsigned Opcode,
1400                                                TTI::TargetCostKind CostKind,
1401                                                const Instruction *I) {
1402   if (CostKind != TTI::TCK_RecipThroughput)
1403     return Opcode == Instruction::PHI ? 0 : 1;
1404   assert(CostKind == TTI::TCK_RecipThroughput && "unexpected CostKind");
1405   // Branches are assumed to be predicted.
1406   return 0;
1407 }
1408 
1409 InstructionCost AArch64TTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val,
1410                                                    unsigned Index) {
1411   assert(Val->isVectorTy() && "This must be a vector type");
1412 
1413   if (Index != -1U) {
1414     // Legalize the type.
1415     std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Val);
1416 
1417     // This type is legalized to a scalar type.
1418     if (!LT.second.isVector())
1419       return 0;
1420 
1421     // The type may be split. Normalize the index to the new type.
1422     unsigned Width = LT.second.getVectorNumElements();
1423     Index = Index % Width;
1424 
1425     // The element at index zero is already inside the vector.
1426     if (Index == 0)
1427       return 0;
1428   }
1429 
1430   // All other insert/extracts cost this much.
1431   return ST->getVectorInsertExtractBaseCost();
1432 }
1433 
1434 InstructionCost AArch64TTIImpl::getArithmeticInstrCost(
1435     unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
1436     TTI::OperandValueKind Opd1Info, TTI::OperandValueKind Opd2Info,
1437     TTI::OperandValueProperties Opd1PropInfo,
1438     TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args,
1439     const Instruction *CxtI) {
1440   // TODO: Handle more cost kinds.
1441   if (CostKind != TTI::TCK_RecipThroughput)
1442     return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info,
1443                                          Opd2Info, Opd1PropInfo,
1444                                          Opd2PropInfo, Args, CxtI);
1445 
1446   // Legalize the type.
1447   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
1448 
1449   // If the instruction is a widening instruction (e.g., uaddl, saddw, etc.),
1450   // add in the widening overhead specified by the sub-target. Since the
1451   // extends feeding widening instructions are performed automatically, they
1452   // aren't present in the generated code and have a zero cost. By adding a
1453   // widening overhead here, we attach the total cost of the combined operation
1454   // to the widening instruction.
1455   InstructionCost Cost = 0;
1456   if (isWideningInstruction(Ty, Opcode, Args))
1457     Cost += ST->getWideningBaseCost();
1458 
1459   int ISD = TLI->InstructionOpcodeToISD(Opcode);
1460 
1461   switch (ISD) {
1462   default:
1463     return Cost + BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info,
1464                                                 Opd2Info,
1465                                                 Opd1PropInfo, Opd2PropInfo);
1466   case ISD::SDIV:
1467     if (Opd2Info == TargetTransformInfo::OK_UniformConstantValue &&
1468         Opd2PropInfo == TargetTransformInfo::OP_PowerOf2) {
1469       // On AArch64, scalar signed division by constants power-of-two are
1470       // normally expanded to the sequence ADD + CMP + SELECT + SRA.
1471       // The OperandValue properties many not be same as that of previous
1472       // operation; conservatively assume OP_None.
1473       Cost += getArithmeticInstrCost(Instruction::Add, Ty, CostKind,
1474                                      Opd1Info, Opd2Info,
1475                                      TargetTransformInfo::OP_None,
1476                                      TargetTransformInfo::OP_None);
1477       Cost += getArithmeticInstrCost(Instruction::Sub, Ty, CostKind,
1478                                      Opd1Info, Opd2Info,
1479                                      TargetTransformInfo::OP_None,
1480                                      TargetTransformInfo::OP_None);
1481       Cost += getArithmeticInstrCost(Instruction::Select, Ty, CostKind,
1482                                      Opd1Info, Opd2Info,
1483                                      TargetTransformInfo::OP_None,
1484                                      TargetTransformInfo::OP_None);
1485       Cost += getArithmeticInstrCost(Instruction::AShr, Ty, CostKind,
1486                                      Opd1Info, Opd2Info,
1487                                      TargetTransformInfo::OP_None,
1488                                      TargetTransformInfo::OP_None);
1489       return Cost;
1490     }
1491     LLVM_FALLTHROUGH;
1492   case ISD::UDIV:
1493     if (Opd2Info == TargetTransformInfo::OK_UniformConstantValue) {
1494       auto VT = TLI->getValueType(DL, Ty);
1495       if (TLI->isOperationLegalOrCustom(ISD::MULHU, VT)) {
1496         // Vector signed division by constant are expanded to the
1497         // sequence MULHS + ADD/SUB + SRA + SRL + ADD, and unsigned division
1498         // to MULHS + SUB + SRL + ADD + SRL.
1499         InstructionCost MulCost = getArithmeticInstrCost(
1500             Instruction::Mul, Ty, CostKind, Opd1Info, Opd2Info,
1501             TargetTransformInfo::OP_None, TargetTransformInfo::OP_None);
1502         InstructionCost AddCost = getArithmeticInstrCost(
1503             Instruction::Add, Ty, CostKind, Opd1Info, Opd2Info,
1504             TargetTransformInfo::OP_None, TargetTransformInfo::OP_None);
1505         InstructionCost ShrCost = getArithmeticInstrCost(
1506             Instruction::AShr, Ty, CostKind, Opd1Info, Opd2Info,
1507             TargetTransformInfo::OP_None, TargetTransformInfo::OP_None);
1508         return MulCost * 2 + AddCost * 2 + ShrCost * 2 + 1;
1509       }
1510     }
1511 
1512     Cost += BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info,
1513                                           Opd2Info,
1514                                           Opd1PropInfo, Opd2PropInfo);
1515     if (Ty->isVectorTy()) {
1516       // On AArch64, vector divisions are not supported natively and are
1517       // expanded into scalar divisions of each pair of elements.
1518       Cost += getArithmeticInstrCost(Instruction::ExtractElement, Ty, CostKind,
1519                                      Opd1Info, Opd2Info, Opd1PropInfo,
1520                                      Opd2PropInfo);
1521       Cost += getArithmeticInstrCost(Instruction::InsertElement, Ty, CostKind,
1522                                      Opd1Info, Opd2Info, Opd1PropInfo,
1523                                      Opd2PropInfo);
1524       // TODO: if one of the arguments is scalar, then it's not necessary to
1525       // double the cost of handling the vector elements.
1526       Cost += Cost;
1527     }
1528     return Cost;
1529 
1530   case ISD::MUL:
1531     if (LT.second != MVT::v2i64)
1532       return (Cost + 1) * LT.first;
1533     // Since we do not have a MUL.2d instruction, a mul <2 x i64> is expensive
1534     // as elements are extracted from the vectors and the muls scalarized.
1535     // As getScalarizationOverhead is a bit too pessimistic, we estimate the
1536     // cost for a i64 vector directly here, which is:
1537     // - four i64 extracts,
1538     // - two i64 inserts, and
1539     // - two muls.
1540     // So, for a v2i64 with LT.First = 1 the cost is 8, and for a v4i64 with
1541     // LT.first = 2 the cost is 16.
1542     return LT.first * 8;
1543   case ISD::ADD:
1544   case ISD::XOR:
1545   case ISD::OR:
1546   case ISD::AND:
1547     // These nodes are marked as 'custom' for combining purposes only.
1548     // We know that they are legal. See LowerAdd in ISelLowering.
1549     return (Cost + 1) * LT.first;
1550 
1551   case ISD::FADD:
1552   case ISD::FSUB:
1553   case ISD::FMUL:
1554   case ISD::FDIV:
1555   case ISD::FNEG:
1556     // These nodes are marked as 'custom' just to lower them to SVE.
1557     // We know said lowering will incur no additional cost.
1558     if (!Ty->getScalarType()->isFP128Ty())
1559       return (Cost + 2) * LT.first;
1560 
1561     return Cost + BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info,
1562                                                 Opd2Info,
1563                                                 Opd1PropInfo, Opd2PropInfo);
1564   }
1565 }
1566 
1567 InstructionCost AArch64TTIImpl::getAddressComputationCost(Type *Ty,
1568                                                           ScalarEvolution *SE,
1569                                                           const SCEV *Ptr) {
1570   // Address computations in vectorized code with non-consecutive addresses will
1571   // likely result in more instructions compared to scalar code where the
1572   // computation can more often be merged into the index mode. The resulting
1573   // extra micro-ops can significantly decrease throughput.
1574   unsigned NumVectorInstToHideOverhead = 10;
1575   int MaxMergeDistance = 64;
1576 
1577   if (Ty->isVectorTy() && SE &&
1578       !BaseT::isConstantStridedAccessLessThan(SE, Ptr, MaxMergeDistance + 1))
1579     return NumVectorInstToHideOverhead;
1580 
1581   // In many cases the address computation is not merged into the instruction
1582   // addressing mode.
1583   return 1;
1584 }
1585 
1586 InstructionCost AArch64TTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
1587                                                    Type *CondTy,
1588                                                    CmpInst::Predicate VecPred,
1589                                                    TTI::TargetCostKind CostKind,
1590                                                    const Instruction *I) {
1591   // TODO: Handle other cost kinds.
1592   if (CostKind != TTI::TCK_RecipThroughput)
1593     return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind,
1594                                      I);
1595 
1596   int ISD = TLI->InstructionOpcodeToISD(Opcode);
1597   // We don't lower some vector selects well that are wider than the register
1598   // width.
1599   if (isa<FixedVectorType>(ValTy) && ISD == ISD::SELECT) {
1600     // We would need this many instructions to hide the scalarization happening.
1601     const int AmortizationCost = 20;
1602 
1603     // If VecPred is not set, check if we can get a predicate from the context
1604     // instruction, if its type matches the requested ValTy.
1605     if (VecPred == CmpInst::BAD_ICMP_PREDICATE && I && I->getType() == ValTy) {
1606       CmpInst::Predicate CurrentPred;
1607       if (match(I, m_Select(m_Cmp(CurrentPred, m_Value(), m_Value()), m_Value(),
1608                             m_Value())))
1609         VecPred = CurrentPred;
1610     }
1611     // Check if we have a compare/select chain that can be lowered using CMxx &
1612     // BFI pair.
1613     if (CmpInst::isIntPredicate(VecPred)) {
1614       static const auto ValidMinMaxTys = {MVT::v8i8,  MVT::v16i8, MVT::v4i16,
1615                                           MVT::v8i16, MVT::v2i32, MVT::v4i32,
1616                                           MVT::v2i64};
1617       auto LT = TLI->getTypeLegalizationCost(DL, ValTy);
1618       if (any_of(ValidMinMaxTys, [&LT](MVT M) { return M == LT.second; }))
1619         return LT.first;
1620     }
1621 
1622     static const TypeConversionCostTblEntry
1623     VectorSelectTbl[] = {
1624       { ISD::SELECT, MVT::v16i1, MVT::v16i16, 16 },
1625       { ISD::SELECT, MVT::v8i1, MVT::v8i32, 8 },
1626       { ISD::SELECT, MVT::v16i1, MVT::v16i32, 16 },
1627       { ISD::SELECT, MVT::v4i1, MVT::v4i64, 4 * AmortizationCost },
1628       { ISD::SELECT, MVT::v8i1, MVT::v8i64, 8 * AmortizationCost },
1629       { ISD::SELECT, MVT::v16i1, MVT::v16i64, 16 * AmortizationCost }
1630     };
1631 
1632     EVT SelCondTy = TLI->getValueType(DL, CondTy);
1633     EVT SelValTy = TLI->getValueType(DL, ValTy);
1634     if (SelCondTy.isSimple() && SelValTy.isSimple()) {
1635       if (const auto *Entry = ConvertCostTableLookup(VectorSelectTbl, ISD,
1636                                                      SelCondTy.getSimpleVT(),
1637                                                      SelValTy.getSimpleVT()))
1638         return Entry->Cost;
1639     }
1640   }
1641   // The base case handles scalable vectors fine for now, since it treats the
1642   // cost as 1 * legalization cost.
1643   return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind, I);
1644 }
1645 
1646 AArch64TTIImpl::TTI::MemCmpExpansionOptions
1647 AArch64TTIImpl::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const {
1648   TTI::MemCmpExpansionOptions Options;
1649   if (ST->requiresStrictAlign()) {
1650     // TODO: Add cost modeling for strict align. Misaligned loads expand to
1651     // a bunch of instructions when strict align is enabled.
1652     return Options;
1653   }
1654   Options.AllowOverlappingLoads = true;
1655   Options.MaxNumLoads = TLI->getMaxExpandSizeMemcmp(OptSize);
1656   Options.NumLoadsPerBlock = Options.MaxNumLoads;
1657   // TODO: Though vector loads usually perform well on AArch64, in some targets
1658   // they may wake up the FP unit, which raises the power consumption.  Perhaps
1659   // they could be used with no holds barred (-O3).
1660   Options.LoadSizes = {8, 4, 2, 1};
1661   return Options;
1662 }
1663 
1664 InstructionCost
1665 AArch64TTIImpl::getMaskedMemoryOpCost(unsigned Opcode, Type *Src,
1666                                       Align Alignment, unsigned AddressSpace,
1667                                       TTI::TargetCostKind CostKind) {
1668   if (!isa<ScalableVectorType>(Src))
1669     return BaseT::getMaskedMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
1670                                         CostKind);
1671   auto LT = TLI->getTypeLegalizationCost(DL, Src);
1672   if (!LT.first.isValid())
1673     return InstructionCost::getInvalid();
1674 
1675   // The code-generator is currently not able to handle scalable vectors
1676   // of <vscale x 1 x eltty> yet, so return an invalid cost to avoid selecting
1677   // it. This change will be removed when code-generation for these types is
1678   // sufficiently reliable.
1679   if (cast<VectorType>(Src)->getElementCount() == ElementCount::getScalable(1))
1680     return InstructionCost::getInvalid();
1681 
1682   return LT.first * 2;
1683 }
1684 
1685 InstructionCost AArch64TTIImpl::getGatherScatterOpCost(
1686     unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask,
1687     Align Alignment, TTI::TargetCostKind CostKind, const Instruction *I) {
1688   if (useNeonVector(DataTy))
1689     return BaseT::getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
1690                                          Alignment, CostKind, I);
1691   auto *VT = cast<VectorType>(DataTy);
1692   auto LT = TLI->getTypeLegalizationCost(DL, DataTy);
1693   if (!LT.first.isValid())
1694     return InstructionCost::getInvalid();
1695 
1696   // The code-generator is currently not able to handle scalable vectors
1697   // of <vscale x 1 x eltty> yet, so return an invalid cost to avoid selecting
1698   // it. This change will be removed when code-generation for these types is
1699   // sufficiently reliable.
1700   if (cast<VectorType>(DataTy)->getElementCount() ==
1701       ElementCount::getScalable(1))
1702     return InstructionCost::getInvalid();
1703 
1704   ElementCount LegalVF = LT.second.getVectorElementCount();
1705   InstructionCost MemOpCost =
1706       getMemoryOpCost(Opcode, VT->getElementType(), Alignment, 0, CostKind, I);
1707   return LT.first * MemOpCost * getMaxNumElements(LegalVF);
1708 }
1709 
1710 bool AArch64TTIImpl::useNeonVector(const Type *Ty) const {
1711   return isa<FixedVectorType>(Ty) && !ST->useSVEForFixedLengthVectors();
1712 }
1713 
1714 InstructionCost AArch64TTIImpl::getMemoryOpCost(unsigned Opcode, Type *Ty,
1715                                                 MaybeAlign Alignment,
1716                                                 unsigned AddressSpace,
1717                                                 TTI::TargetCostKind CostKind,
1718                                                 const Instruction *I) {
1719   EVT VT = TLI->getValueType(DL, Ty, true);
1720   // Type legalization can't handle structs
1721   if (VT == MVT::Other)
1722     return BaseT::getMemoryOpCost(Opcode, Ty, Alignment, AddressSpace,
1723                                   CostKind);
1724 
1725   auto LT = TLI->getTypeLegalizationCost(DL, Ty);
1726   if (!LT.first.isValid())
1727     return InstructionCost::getInvalid();
1728 
1729   // The code-generator is currently not able to handle scalable vectors
1730   // of <vscale x 1 x eltty> yet, so return an invalid cost to avoid selecting
1731   // it. This change will be removed when code-generation for these types is
1732   // sufficiently reliable.
1733   if (auto *VTy = dyn_cast<ScalableVectorType>(Ty))
1734     if (VTy->getElementCount() == ElementCount::getScalable(1))
1735       return InstructionCost::getInvalid();
1736 
1737   // TODO: consider latency as well for TCK_SizeAndLatency.
1738   if (CostKind == TTI::TCK_CodeSize || CostKind == TTI::TCK_SizeAndLatency)
1739     return LT.first;
1740 
1741   if (CostKind != TTI::TCK_RecipThroughput)
1742     return 1;
1743 
1744   if (ST->isMisaligned128StoreSlow() && Opcode == Instruction::Store &&
1745       LT.second.is128BitVector() && (!Alignment || *Alignment < Align(16))) {
1746     // Unaligned stores are extremely inefficient. We don't split all
1747     // unaligned 128-bit stores because the negative impact that has shown in
1748     // practice on inlined block copy code.
1749     // We make such stores expensive so that we will only vectorize if there
1750     // are 6 other instructions getting vectorized.
1751     const int AmortizationCost = 6;
1752 
1753     return LT.first * 2 * AmortizationCost;
1754   }
1755 
1756   // Check truncating stores and extending loads.
1757   if (useNeonVector(Ty) &&
1758       Ty->getScalarSizeInBits() != LT.second.getScalarSizeInBits()) {
1759     // v4i8 types are lowered to scalar a load/store and sshll/xtn.
1760     if (VT == MVT::v4i8)
1761       return 2;
1762     // Otherwise we need to scalarize.
1763     return cast<FixedVectorType>(Ty)->getNumElements() * 2;
1764   }
1765 
1766   return LT.first;
1767 }
1768 
1769 InstructionCost AArch64TTIImpl::getInterleavedMemoryOpCost(
1770     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
1771     Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
1772     bool UseMaskForCond, bool UseMaskForGaps) {
1773   assert(Factor >= 2 && "Invalid interleave factor");
1774   auto *VecVTy = cast<FixedVectorType>(VecTy);
1775 
1776   if (!UseMaskForCond && !UseMaskForGaps &&
1777       Factor <= TLI->getMaxSupportedInterleaveFactor()) {
1778     unsigned NumElts = VecVTy->getNumElements();
1779     auto *SubVecTy =
1780         FixedVectorType::get(VecTy->getScalarType(), NumElts / Factor);
1781 
1782     // ldN/stN only support legal vector types of size 64 or 128 in bits.
1783     // Accesses having vector types that are a multiple of 128 bits can be
1784     // matched to more than one ldN/stN instruction.
1785     bool UseScalable;
1786     if (NumElts % Factor == 0 &&
1787         TLI->isLegalInterleavedAccessType(SubVecTy, DL, UseScalable))
1788       return Factor * TLI->getNumInterleavedAccesses(SubVecTy, DL, UseScalable);
1789   }
1790 
1791   return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
1792                                            Alignment, AddressSpace, CostKind,
1793                                            UseMaskForCond, UseMaskForGaps);
1794 }
1795 
1796 InstructionCost
1797 AArch64TTIImpl::getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) {
1798   InstructionCost Cost = 0;
1799   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
1800   for (auto *I : Tys) {
1801     if (!I->isVectorTy())
1802       continue;
1803     if (I->getScalarSizeInBits() * cast<FixedVectorType>(I)->getNumElements() ==
1804         128)
1805       Cost += getMemoryOpCost(Instruction::Store, I, Align(128), 0, CostKind) +
1806               getMemoryOpCost(Instruction::Load, I, Align(128), 0, CostKind);
1807   }
1808   return Cost;
1809 }
1810 
1811 unsigned AArch64TTIImpl::getMaxInterleaveFactor(unsigned VF) {
1812   return ST->getMaxInterleaveFactor();
1813 }
1814 
1815 // For Falkor, we want to avoid having too many strided loads in a loop since
1816 // that can exhaust the HW prefetcher resources.  We adjust the unroller
1817 // MaxCount preference below to attempt to ensure unrolling doesn't create too
1818 // many strided loads.
1819 static void
1820 getFalkorUnrollingPreferences(Loop *L, ScalarEvolution &SE,
1821                               TargetTransformInfo::UnrollingPreferences &UP) {
1822   enum { MaxStridedLoads = 7 };
1823   auto countStridedLoads = [](Loop *L, ScalarEvolution &SE) {
1824     int StridedLoads = 0;
1825     // FIXME? We could make this more precise by looking at the CFG and
1826     // e.g. not counting loads in each side of an if-then-else diamond.
1827     for (const auto BB : L->blocks()) {
1828       for (auto &I : *BB) {
1829         LoadInst *LMemI = dyn_cast<LoadInst>(&I);
1830         if (!LMemI)
1831           continue;
1832 
1833         Value *PtrValue = LMemI->getPointerOperand();
1834         if (L->isLoopInvariant(PtrValue))
1835           continue;
1836 
1837         const SCEV *LSCEV = SE.getSCEV(PtrValue);
1838         const SCEVAddRecExpr *LSCEVAddRec = dyn_cast<SCEVAddRecExpr>(LSCEV);
1839         if (!LSCEVAddRec || !LSCEVAddRec->isAffine())
1840           continue;
1841 
1842         // FIXME? We could take pairing of unrolled load copies into account
1843         // by looking at the AddRec, but we would probably have to limit this
1844         // to loops with no stores or other memory optimization barriers.
1845         ++StridedLoads;
1846         // We've seen enough strided loads that seeing more won't make a
1847         // difference.
1848         if (StridedLoads > MaxStridedLoads / 2)
1849           return StridedLoads;
1850       }
1851     }
1852     return StridedLoads;
1853   };
1854 
1855   int StridedLoads = countStridedLoads(L, SE);
1856   LLVM_DEBUG(dbgs() << "falkor-hwpf: detected " << StridedLoads
1857                     << " strided loads\n");
1858   // Pick the largest power of 2 unroll count that won't result in too many
1859   // strided loads.
1860   if (StridedLoads) {
1861     UP.MaxCount = 1 << Log2_32(MaxStridedLoads / StridedLoads);
1862     LLVM_DEBUG(dbgs() << "falkor-hwpf: setting unroll MaxCount to "
1863                       << UP.MaxCount << '\n');
1864   }
1865 }
1866 
1867 void AArch64TTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
1868                                              TTI::UnrollingPreferences &UP,
1869                                              OptimizationRemarkEmitter *ORE) {
1870   // Enable partial unrolling and runtime unrolling.
1871   BaseT::getUnrollingPreferences(L, SE, UP, ORE);
1872 
1873   UP.UpperBound = true;
1874 
1875   // For inner loop, it is more likely to be a hot one, and the runtime check
1876   // can be promoted out from LICM pass, so the overhead is less, let's try
1877   // a larger threshold to unroll more loops.
1878   if (L->getLoopDepth() > 1)
1879     UP.PartialThreshold *= 2;
1880 
1881   // Disable partial & runtime unrolling on -Os.
1882   UP.PartialOptSizeThreshold = 0;
1883 
1884   if (ST->getProcFamily() == AArch64Subtarget::Falkor &&
1885       EnableFalkorHWPFUnrollFix)
1886     getFalkorUnrollingPreferences(L, SE, UP);
1887 
1888   // Scan the loop: don't unroll loops with calls as this could prevent
1889   // inlining. Don't unroll vector loops either, as they don't benefit much from
1890   // unrolling.
1891   for (auto *BB : L->getBlocks()) {
1892     for (auto &I : *BB) {
1893       // Don't unroll vectorised loop.
1894       if (I.getType()->isVectorTy())
1895         return;
1896 
1897       if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
1898         if (const Function *F = cast<CallBase>(I).getCalledFunction()) {
1899           if (!isLoweredToCall(F))
1900             continue;
1901         }
1902         return;
1903       }
1904     }
1905   }
1906 
1907   // Enable runtime unrolling for in-order models
1908   // If mcpu is omitted, getProcFamily() returns AArch64Subtarget::Others, so by
1909   // checking for that case, we can ensure that the default behaviour is
1910   // unchanged
1911   if (ST->getProcFamily() != AArch64Subtarget::Others &&
1912       !ST->getSchedModel().isOutOfOrder()) {
1913     UP.Runtime = true;
1914     UP.Partial = true;
1915     UP.UnrollRemainder = true;
1916     UP.DefaultUnrollRuntimeCount = 4;
1917 
1918     UP.UnrollAndJam = true;
1919     UP.UnrollAndJamInnerLoopThreshold = 60;
1920   }
1921 }
1922 
1923 void AArch64TTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
1924                                            TTI::PeelingPreferences &PP) {
1925   BaseT::getPeelingPreferences(L, SE, PP);
1926 }
1927 
1928 Value *AArch64TTIImpl::getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
1929                                                          Type *ExpectedType) {
1930   switch (Inst->getIntrinsicID()) {
1931   default:
1932     return nullptr;
1933   case Intrinsic::aarch64_neon_st2:
1934   case Intrinsic::aarch64_neon_st3:
1935   case Intrinsic::aarch64_neon_st4: {
1936     // Create a struct type
1937     StructType *ST = dyn_cast<StructType>(ExpectedType);
1938     if (!ST)
1939       return nullptr;
1940     unsigned NumElts = Inst->arg_size() - 1;
1941     if (ST->getNumElements() != NumElts)
1942       return nullptr;
1943     for (unsigned i = 0, e = NumElts; i != e; ++i) {
1944       if (Inst->getArgOperand(i)->getType() != ST->getElementType(i))
1945         return nullptr;
1946     }
1947     Value *Res = UndefValue::get(ExpectedType);
1948     IRBuilder<> Builder(Inst);
1949     for (unsigned i = 0, e = NumElts; i != e; ++i) {
1950       Value *L = Inst->getArgOperand(i);
1951       Res = Builder.CreateInsertValue(Res, L, i);
1952     }
1953     return Res;
1954   }
1955   case Intrinsic::aarch64_neon_ld2:
1956   case Intrinsic::aarch64_neon_ld3:
1957   case Intrinsic::aarch64_neon_ld4:
1958     if (Inst->getType() == ExpectedType)
1959       return Inst;
1960     return nullptr;
1961   }
1962 }
1963 
1964 bool AArch64TTIImpl::getTgtMemIntrinsic(IntrinsicInst *Inst,
1965                                         MemIntrinsicInfo &Info) {
1966   switch (Inst->getIntrinsicID()) {
1967   default:
1968     break;
1969   case Intrinsic::aarch64_neon_ld2:
1970   case Intrinsic::aarch64_neon_ld3:
1971   case Intrinsic::aarch64_neon_ld4:
1972     Info.ReadMem = true;
1973     Info.WriteMem = false;
1974     Info.PtrVal = Inst->getArgOperand(0);
1975     break;
1976   case Intrinsic::aarch64_neon_st2:
1977   case Intrinsic::aarch64_neon_st3:
1978   case Intrinsic::aarch64_neon_st4:
1979     Info.ReadMem = false;
1980     Info.WriteMem = true;
1981     Info.PtrVal = Inst->getArgOperand(Inst->arg_size() - 1);
1982     break;
1983   }
1984 
1985   switch (Inst->getIntrinsicID()) {
1986   default:
1987     return false;
1988   case Intrinsic::aarch64_neon_ld2:
1989   case Intrinsic::aarch64_neon_st2:
1990     Info.MatchingId = VECTOR_LDST_TWO_ELEMENTS;
1991     break;
1992   case Intrinsic::aarch64_neon_ld3:
1993   case Intrinsic::aarch64_neon_st3:
1994     Info.MatchingId = VECTOR_LDST_THREE_ELEMENTS;
1995     break;
1996   case Intrinsic::aarch64_neon_ld4:
1997   case Intrinsic::aarch64_neon_st4:
1998     Info.MatchingId = VECTOR_LDST_FOUR_ELEMENTS;
1999     break;
2000   }
2001   return true;
2002 }
2003 
2004 /// See if \p I should be considered for address type promotion. We check if \p
2005 /// I is a sext with right type and used in memory accesses. If it used in a
2006 /// "complex" getelementptr, we allow it to be promoted without finding other
2007 /// sext instructions that sign extended the same initial value. A getelementptr
2008 /// is considered as "complex" if it has more than 2 operands.
2009 bool AArch64TTIImpl::shouldConsiderAddressTypePromotion(
2010     const Instruction &I, bool &AllowPromotionWithoutCommonHeader) {
2011   bool Considerable = false;
2012   AllowPromotionWithoutCommonHeader = false;
2013   if (!isa<SExtInst>(&I))
2014     return false;
2015   Type *ConsideredSExtType =
2016       Type::getInt64Ty(I.getParent()->getParent()->getContext());
2017   if (I.getType() != ConsideredSExtType)
2018     return false;
2019   // See if the sext is the one with the right type and used in at least one
2020   // GetElementPtrInst.
2021   for (const User *U : I.users()) {
2022     if (const GetElementPtrInst *GEPInst = dyn_cast<GetElementPtrInst>(U)) {
2023       Considerable = true;
2024       // A getelementptr is considered as "complex" if it has more than 2
2025       // operands. We will promote a SExt used in such complex GEP as we
2026       // expect some computation to be merged if they are done on 64 bits.
2027       if (GEPInst->getNumOperands() > 2) {
2028         AllowPromotionWithoutCommonHeader = true;
2029         break;
2030       }
2031     }
2032   }
2033   return Considerable;
2034 }
2035 
2036 bool AArch64TTIImpl::isLegalToVectorizeReduction(
2037     const RecurrenceDescriptor &RdxDesc, ElementCount VF) const {
2038   if (!VF.isScalable())
2039     return true;
2040 
2041   Type *Ty = RdxDesc.getRecurrenceType();
2042   if (Ty->isBFloatTy() || !isElementTypeLegalForScalableVector(Ty))
2043     return false;
2044 
2045   switch (RdxDesc.getRecurrenceKind()) {
2046   case RecurKind::Add:
2047   case RecurKind::FAdd:
2048   case RecurKind::And:
2049   case RecurKind::Or:
2050   case RecurKind::Xor:
2051   case RecurKind::SMin:
2052   case RecurKind::SMax:
2053   case RecurKind::UMin:
2054   case RecurKind::UMax:
2055   case RecurKind::FMin:
2056   case RecurKind::FMax:
2057   case RecurKind::SelectICmp:
2058   case RecurKind::SelectFCmp:
2059     return true;
2060   default:
2061     return false;
2062   }
2063 }
2064 
2065 InstructionCost
2066 AArch64TTIImpl::getMinMaxReductionCost(VectorType *Ty, VectorType *CondTy,
2067                                        bool IsUnsigned,
2068                                        TTI::TargetCostKind CostKind) {
2069   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
2070 
2071   if (LT.second.getScalarType() == MVT::f16 && !ST->hasFullFP16())
2072     return BaseT::getMinMaxReductionCost(Ty, CondTy, IsUnsigned, CostKind);
2073 
2074   assert((isa<ScalableVectorType>(Ty) == isa<ScalableVectorType>(CondTy)) &&
2075          "Both vector needs to be equally scalable");
2076 
2077   InstructionCost LegalizationCost = 0;
2078   if (LT.first > 1) {
2079     Type *LegalVTy = EVT(LT.second).getTypeForEVT(Ty->getContext());
2080     unsigned MinMaxOpcode =
2081         Ty->isFPOrFPVectorTy()
2082             ? Intrinsic::maxnum
2083             : (IsUnsigned ? Intrinsic::umin : Intrinsic::smin);
2084     IntrinsicCostAttributes Attrs(MinMaxOpcode, LegalVTy, {LegalVTy, LegalVTy});
2085     LegalizationCost = getIntrinsicInstrCost(Attrs, CostKind) * (LT.first - 1);
2086   }
2087 
2088   return LegalizationCost + /*Cost of horizontal reduction*/ 2;
2089 }
2090 
2091 InstructionCost AArch64TTIImpl::getArithmeticReductionCostSVE(
2092     unsigned Opcode, VectorType *ValTy, TTI::TargetCostKind CostKind) {
2093   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
2094   InstructionCost LegalizationCost = 0;
2095   if (LT.first > 1) {
2096     Type *LegalVTy = EVT(LT.second).getTypeForEVT(ValTy->getContext());
2097     LegalizationCost = getArithmeticInstrCost(Opcode, LegalVTy, CostKind);
2098     LegalizationCost *= LT.first - 1;
2099   }
2100 
2101   int ISD = TLI->InstructionOpcodeToISD(Opcode);
2102   assert(ISD && "Invalid opcode");
2103   // Add the final reduction cost for the legal horizontal reduction
2104   switch (ISD) {
2105   case ISD::ADD:
2106   case ISD::AND:
2107   case ISD::OR:
2108   case ISD::XOR:
2109   case ISD::FADD:
2110     return LegalizationCost + 2;
2111   default:
2112     return InstructionCost::getInvalid();
2113   }
2114 }
2115 
2116 InstructionCost
2117 AArch64TTIImpl::getArithmeticReductionCost(unsigned Opcode, VectorType *ValTy,
2118                                            Optional<FastMathFlags> FMF,
2119                                            TTI::TargetCostKind CostKind) {
2120   if (TTI::requiresOrderedReduction(FMF)) {
2121     if (auto *FixedVTy = dyn_cast<FixedVectorType>(ValTy)) {
2122       InstructionCost BaseCost =
2123           BaseT::getArithmeticReductionCost(Opcode, ValTy, FMF, CostKind);
2124       // Add on extra cost to reflect the extra overhead on some CPUs. We still
2125       // end up vectorizing for more computationally intensive loops.
2126       return BaseCost + FixedVTy->getNumElements();
2127     }
2128 
2129     if (Opcode != Instruction::FAdd)
2130       return InstructionCost::getInvalid();
2131 
2132     auto *VTy = cast<ScalableVectorType>(ValTy);
2133     InstructionCost Cost =
2134         getArithmeticInstrCost(Opcode, VTy->getScalarType(), CostKind);
2135     Cost *= getMaxNumElements(VTy->getElementCount());
2136     return Cost;
2137   }
2138 
2139   if (isa<ScalableVectorType>(ValTy))
2140     return getArithmeticReductionCostSVE(Opcode, ValTy, CostKind);
2141 
2142   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
2143   MVT MTy = LT.second;
2144   int ISD = TLI->InstructionOpcodeToISD(Opcode);
2145   assert(ISD && "Invalid opcode");
2146 
2147   // Horizontal adds can use the 'addv' instruction. We model the cost of these
2148   // instructions as twice a normal vector add, plus 1 for each legalization
2149   // step (LT.first). This is the only arithmetic vector reduction operation for
2150   // which we have an instruction.
2151   // OR, XOR and AND costs should match the codegen from:
2152   // OR: llvm/test/CodeGen/AArch64/reduce-or.ll
2153   // XOR: llvm/test/CodeGen/AArch64/reduce-xor.ll
2154   // AND: llvm/test/CodeGen/AArch64/reduce-and.ll
2155   static const CostTblEntry CostTblNoPairwise[]{
2156       {ISD::ADD, MVT::v8i8,   2},
2157       {ISD::ADD, MVT::v16i8,  2},
2158       {ISD::ADD, MVT::v4i16,  2},
2159       {ISD::ADD, MVT::v8i16,  2},
2160       {ISD::ADD, MVT::v4i32,  2},
2161       {ISD::OR,  MVT::v8i8,  15},
2162       {ISD::OR,  MVT::v16i8, 17},
2163       {ISD::OR,  MVT::v4i16,  7},
2164       {ISD::OR,  MVT::v8i16,  9},
2165       {ISD::OR,  MVT::v2i32,  3},
2166       {ISD::OR,  MVT::v4i32,  5},
2167       {ISD::OR,  MVT::v2i64,  3},
2168       {ISD::XOR, MVT::v8i8,  15},
2169       {ISD::XOR, MVT::v16i8, 17},
2170       {ISD::XOR, MVT::v4i16,  7},
2171       {ISD::XOR, MVT::v8i16,  9},
2172       {ISD::XOR, MVT::v2i32,  3},
2173       {ISD::XOR, MVT::v4i32,  5},
2174       {ISD::XOR, MVT::v2i64,  3},
2175       {ISD::AND, MVT::v8i8,  15},
2176       {ISD::AND, MVT::v16i8, 17},
2177       {ISD::AND, MVT::v4i16,  7},
2178       {ISD::AND, MVT::v8i16,  9},
2179       {ISD::AND, MVT::v2i32,  3},
2180       {ISD::AND, MVT::v4i32,  5},
2181       {ISD::AND, MVT::v2i64,  3},
2182   };
2183   switch (ISD) {
2184   default:
2185     break;
2186   case ISD::ADD:
2187     if (const auto *Entry = CostTableLookup(CostTblNoPairwise, ISD, MTy))
2188       return (LT.first - 1) + Entry->Cost;
2189     break;
2190   case ISD::XOR:
2191   case ISD::AND:
2192   case ISD::OR:
2193     const auto *Entry = CostTableLookup(CostTblNoPairwise, ISD, MTy);
2194     if (!Entry)
2195       break;
2196     auto *ValVTy = cast<FixedVectorType>(ValTy);
2197     if (!ValVTy->getElementType()->isIntegerTy(1) &&
2198         MTy.getVectorNumElements() <= ValVTy->getNumElements() &&
2199         isPowerOf2_32(ValVTy->getNumElements())) {
2200       InstructionCost ExtraCost = 0;
2201       if (LT.first != 1) {
2202         // Type needs to be split, so there is an extra cost of LT.first - 1
2203         // arithmetic ops.
2204         auto *Ty = FixedVectorType::get(ValTy->getElementType(),
2205                                         MTy.getVectorNumElements());
2206         ExtraCost = getArithmeticInstrCost(Opcode, Ty, CostKind);
2207         ExtraCost *= LT.first - 1;
2208       }
2209       return Entry->Cost + ExtraCost;
2210     }
2211     break;
2212   }
2213   return BaseT::getArithmeticReductionCost(Opcode, ValTy, FMF, CostKind);
2214 }
2215 
2216 InstructionCost AArch64TTIImpl::getSpliceCost(VectorType *Tp, int Index) {
2217   static const CostTblEntry ShuffleTbl[] = {
2218       { TTI::SK_Splice, MVT::nxv16i8,  1 },
2219       { TTI::SK_Splice, MVT::nxv8i16,  1 },
2220       { TTI::SK_Splice, MVT::nxv4i32,  1 },
2221       { TTI::SK_Splice, MVT::nxv2i64,  1 },
2222       { TTI::SK_Splice, MVT::nxv2f16,  1 },
2223       { TTI::SK_Splice, MVT::nxv4f16,  1 },
2224       { TTI::SK_Splice, MVT::nxv8f16,  1 },
2225       { TTI::SK_Splice, MVT::nxv2bf16, 1 },
2226       { TTI::SK_Splice, MVT::nxv4bf16, 1 },
2227       { TTI::SK_Splice, MVT::nxv8bf16, 1 },
2228       { TTI::SK_Splice, MVT::nxv2f32,  1 },
2229       { TTI::SK_Splice, MVT::nxv4f32,  1 },
2230       { TTI::SK_Splice, MVT::nxv2f64,  1 },
2231   };
2232 
2233   std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
2234   Type *LegalVTy = EVT(LT.second).getTypeForEVT(Tp->getContext());
2235   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
2236   EVT PromotedVT = LT.second.getScalarType() == MVT::i1
2237                        ? TLI->getPromotedVTForPredicate(EVT(LT.second))
2238                        : LT.second;
2239   Type *PromotedVTy = EVT(PromotedVT).getTypeForEVT(Tp->getContext());
2240   InstructionCost LegalizationCost = 0;
2241   if (Index < 0) {
2242     LegalizationCost =
2243         getCmpSelInstrCost(Instruction::ICmp, PromotedVTy, PromotedVTy,
2244                            CmpInst::BAD_ICMP_PREDICATE, CostKind) +
2245         getCmpSelInstrCost(Instruction::Select, PromotedVTy, LegalVTy,
2246                            CmpInst::BAD_ICMP_PREDICATE, CostKind);
2247   }
2248 
2249   // Predicated splice are promoted when lowering. See AArch64ISelLowering.cpp
2250   // Cost performed on a promoted type.
2251   if (LT.second.getScalarType() == MVT::i1) {
2252     LegalizationCost +=
2253         getCastInstrCost(Instruction::ZExt, PromotedVTy, LegalVTy,
2254                          TTI::CastContextHint::None, CostKind) +
2255         getCastInstrCost(Instruction::Trunc, LegalVTy, PromotedVTy,
2256                          TTI::CastContextHint::None, CostKind);
2257   }
2258   const auto *Entry =
2259       CostTableLookup(ShuffleTbl, TTI::SK_Splice, PromotedVT.getSimpleVT());
2260   assert(Entry && "Illegal Type for Splice");
2261   LegalizationCost += Entry->Cost;
2262   return LegalizationCost * LT.first;
2263 }
2264 
2265 InstructionCost AArch64TTIImpl::getShuffleCost(TTI::ShuffleKind Kind,
2266                                                VectorType *Tp,
2267                                                ArrayRef<int> Mask, int Index,
2268                                                VectorType *SubTp) {
2269   Kind = improveShuffleKindFromMask(Kind, Mask);
2270   if (Kind == TTI::SK_Broadcast || Kind == TTI::SK_Transpose ||
2271       Kind == TTI::SK_Select || Kind == TTI::SK_PermuteSingleSrc ||
2272       Kind == TTI::SK_Reverse) {
2273     static const CostTblEntry ShuffleTbl[] = {
2274       // Broadcast shuffle kinds can be performed with 'dup'.
2275       { TTI::SK_Broadcast, MVT::v8i8,  1 },
2276       { TTI::SK_Broadcast, MVT::v16i8, 1 },
2277       { TTI::SK_Broadcast, MVT::v4i16, 1 },
2278       { TTI::SK_Broadcast, MVT::v8i16, 1 },
2279       { TTI::SK_Broadcast, MVT::v2i32, 1 },
2280       { TTI::SK_Broadcast, MVT::v4i32, 1 },
2281       { TTI::SK_Broadcast, MVT::v2i64, 1 },
2282       { TTI::SK_Broadcast, MVT::v2f32, 1 },
2283       { TTI::SK_Broadcast, MVT::v4f32, 1 },
2284       { TTI::SK_Broadcast, MVT::v2f64, 1 },
2285       // Transpose shuffle kinds can be performed with 'trn1/trn2' and
2286       // 'zip1/zip2' instructions.
2287       { TTI::SK_Transpose, MVT::v8i8,  1 },
2288       { TTI::SK_Transpose, MVT::v16i8, 1 },
2289       { TTI::SK_Transpose, MVT::v4i16, 1 },
2290       { TTI::SK_Transpose, MVT::v8i16, 1 },
2291       { TTI::SK_Transpose, MVT::v2i32, 1 },
2292       { TTI::SK_Transpose, MVT::v4i32, 1 },
2293       { TTI::SK_Transpose, MVT::v2i64, 1 },
2294       { TTI::SK_Transpose, MVT::v2f32, 1 },
2295       { TTI::SK_Transpose, MVT::v4f32, 1 },
2296       { TTI::SK_Transpose, MVT::v2f64, 1 },
2297       // Select shuffle kinds.
2298       // TODO: handle vXi8/vXi16.
2299       { TTI::SK_Select, MVT::v2i32, 1 }, // mov.
2300       { TTI::SK_Select, MVT::v4i32, 2 }, // rev+trn (or similar).
2301       { TTI::SK_Select, MVT::v2i64, 1 }, // mov.
2302       { TTI::SK_Select, MVT::v2f32, 1 }, // mov.
2303       { TTI::SK_Select, MVT::v4f32, 2 }, // rev+trn (or similar).
2304       { TTI::SK_Select, MVT::v2f64, 1 }, // mov.
2305       // PermuteSingleSrc shuffle kinds.
2306       { TTI::SK_PermuteSingleSrc, MVT::v2i32, 1 }, // mov.
2307       { TTI::SK_PermuteSingleSrc, MVT::v4i32, 3 }, // perfectshuffle worst case.
2308       { TTI::SK_PermuteSingleSrc, MVT::v2i64, 1 }, // mov.
2309       { TTI::SK_PermuteSingleSrc, MVT::v2f32, 1 }, // mov.
2310       { TTI::SK_PermuteSingleSrc, MVT::v4f32, 3 }, // perfectshuffle worst case.
2311       { TTI::SK_PermuteSingleSrc, MVT::v2f64, 1 }, // mov.
2312       { TTI::SK_PermuteSingleSrc, MVT::v4i16, 3 }, // perfectshuffle worst case.
2313       { TTI::SK_PermuteSingleSrc, MVT::v4f16, 3 }, // perfectshuffle worst case.
2314       { TTI::SK_PermuteSingleSrc, MVT::v4bf16, 3 }, // perfectshuffle worst case.
2315       { TTI::SK_PermuteSingleSrc, MVT::v8i16, 8 }, // constpool + load + tbl
2316       { TTI::SK_PermuteSingleSrc, MVT::v8f16, 8 }, // constpool + load + tbl
2317       { TTI::SK_PermuteSingleSrc, MVT::v8bf16, 8 }, // constpool + load + tbl
2318       { TTI::SK_PermuteSingleSrc, MVT::v8i8, 8 }, // constpool + load + tbl
2319       { TTI::SK_PermuteSingleSrc, MVT::v16i8, 8 }, // constpool + load + tbl
2320       // Reverse can be lowered with `rev`.
2321       { TTI::SK_Reverse, MVT::v2i32, 1 }, // mov.
2322       { TTI::SK_Reverse, MVT::v4i32, 2 }, // REV64; EXT
2323       { TTI::SK_Reverse, MVT::v2i64, 1 }, // mov.
2324       { TTI::SK_Reverse, MVT::v2f32, 1 }, // mov.
2325       { TTI::SK_Reverse, MVT::v4f32, 2 }, // REV64; EXT
2326       { TTI::SK_Reverse, MVT::v2f64, 1 }, // mov.
2327       // Broadcast shuffle kinds for scalable vectors
2328       { TTI::SK_Broadcast, MVT::nxv16i8,  1 },
2329       { TTI::SK_Broadcast, MVT::nxv8i16,  1 },
2330       { TTI::SK_Broadcast, MVT::nxv4i32,  1 },
2331       { TTI::SK_Broadcast, MVT::nxv2i64,  1 },
2332       { TTI::SK_Broadcast, MVT::nxv2f16,  1 },
2333       { TTI::SK_Broadcast, MVT::nxv4f16,  1 },
2334       { TTI::SK_Broadcast, MVT::nxv8f16,  1 },
2335       { TTI::SK_Broadcast, MVT::nxv2bf16, 1 },
2336       { TTI::SK_Broadcast, MVT::nxv4bf16, 1 },
2337       { TTI::SK_Broadcast, MVT::nxv8bf16, 1 },
2338       { TTI::SK_Broadcast, MVT::nxv2f32,  1 },
2339       { TTI::SK_Broadcast, MVT::nxv4f32,  1 },
2340       { TTI::SK_Broadcast, MVT::nxv2f64,  1 },
2341       { TTI::SK_Broadcast, MVT::nxv16i1,  1 },
2342       { TTI::SK_Broadcast, MVT::nxv8i1,   1 },
2343       { TTI::SK_Broadcast, MVT::nxv4i1,   1 },
2344       { TTI::SK_Broadcast, MVT::nxv2i1,   1 },
2345       // Handle the cases for vector.reverse with scalable vectors
2346       { TTI::SK_Reverse, MVT::nxv16i8,  1 },
2347       { TTI::SK_Reverse, MVT::nxv8i16,  1 },
2348       { TTI::SK_Reverse, MVT::nxv4i32,  1 },
2349       { TTI::SK_Reverse, MVT::nxv2i64,  1 },
2350       { TTI::SK_Reverse, MVT::nxv2f16,  1 },
2351       { TTI::SK_Reverse, MVT::nxv4f16,  1 },
2352       { TTI::SK_Reverse, MVT::nxv8f16,  1 },
2353       { TTI::SK_Reverse, MVT::nxv2bf16, 1 },
2354       { TTI::SK_Reverse, MVT::nxv4bf16, 1 },
2355       { TTI::SK_Reverse, MVT::nxv8bf16, 1 },
2356       { TTI::SK_Reverse, MVT::nxv2f32,  1 },
2357       { TTI::SK_Reverse, MVT::nxv4f32,  1 },
2358       { TTI::SK_Reverse, MVT::nxv2f64,  1 },
2359       { TTI::SK_Reverse, MVT::nxv16i1,  1 },
2360       { TTI::SK_Reverse, MVT::nxv8i1,   1 },
2361       { TTI::SK_Reverse, MVT::nxv4i1,   1 },
2362       { TTI::SK_Reverse, MVT::nxv2i1,   1 },
2363     };
2364     std::pair<InstructionCost, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
2365     if (const auto *Entry = CostTableLookup(ShuffleTbl, Kind, LT.second))
2366       return LT.first * Entry->Cost;
2367   }
2368   if (Kind == TTI::SK_Splice && isa<ScalableVectorType>(Tp))
2369     return getSpliceCost(Tp, Index);
2370   return BaseT::getShuffleCost(Kind, Tp, Mask, Index, SubTp);
2371 }
2372