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