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