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 "AArch64ExpandImm.h"
10 #include "AArch64TargetTransformInfo.h"
11 #include "MCTargetDesc/AArch64AddressingModes.h"
12 #include "llvm/Analysis/LoopInfo.h"
13 #include "llvm/Analysis/TargetTransformInfo.h"
14 #include "llvm/CodeGen/BasicTTIImpl.h"
15 #include "llvm/CodeGen/CostTable.h"
16 #include "llvm/CodeGen/TargetLowering.h"
17 #include "llvm/IR/IntrinsicInst.h"
18 #include "llvm/IR/IntrinsicsAArch64.h"
19 #include "llvm/Support/Debug.h"
20 #include <algorithm>
21 using namespace llvm;
22 
23 #define DEBUG_TYPE "aarch64tti"
24 
25 static cl::opt<bool> EnableFalkorHWPFUnrollFix("enable-falkor-hwpf-unroll-fix",
26                                                cl::init(true), cl::Hidden);
27 
28 bool AArch64TTIImpl::areInlineCompatible(const Function *Caller,
29                                          const Function *Callee) const {
30   const TargetMachine &TM = getTLI()->getTargetMachine();
31 
32   const FeatureBitset &CallerBits =
33       TM.getSubtargetImpl(*Caller)->getFeatureBits();
34   const FeatureBitset &CalleeBits =
35       TM.getSubtargetImpl(*Callee)->getFeatureBits();
36 
37   // Inline a callee if its target-features are a subset of the callers
38   // target-features.
39   return (CallerBits & CalleeBits) == CalleeBits;
40 }
41 
42 /// Calculate the cost of materializing a 64-bit value. This helper
43 /// method might only calculate a fraction of a larger immediate. Therefore it
44 /// is valid to return a cost of ZERO.
45 int AArch64TTIImpl::getIntImmCost(int64_t Val) {
46   // Check if the immediate can be encoded within an instruction.
47   if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, 64))
48     return 0;
49 
50   if (Val < 0)
51     Val = ~Val;
52 
53   // Calculate how many moves we will need to materialize this constant.
54   SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
55   AArch64_IMM::expandMOVImm(Val, 64, Insn);
56   return Insn.size();
57 }
58 
59 /// Calculate the cost of materializing the given constant.
60 int AArch64TTIImpl::getIntImmCost(const APInt &Imm, Type *Ty,
61                                   TTI::TargetCostKind CostKind) {
62   assert(Ty->isIntegerTy());
63 
64   unsigned BitSize = Ty->getPrimitiveSizeInBits();
65   if (BitSize == 0)
66     return ~0U;
67 
68   // Sign-extend all constants to a multiple of 64-bit.
69   APInt ImmVal = Imm;
70   if (BitSize & 0x3f)
71     ImmVal = Imm.sext((BitSize + 63) & ~0x3fU);
72 
73   // Split the constant into 64-bit chunks and calculate the cost for each
74   // chunk.
75   int Cost = 0;
76   for (unsigned ShiftVal = 0; ShiftVal < BitSize; ShiftVal += 64) {
77     APInt Tmp = ImmVal.ashr(ShiftVal).sextOrTrunc(64);
78     int64_t Val = Tmp.getSExtValue();
79     Cost += getIntImmCost(Val);
80   }
81   // We need at least one instruction to materialze the constant.
82   return std::max(1, Cost);
83 }
84 
85 int AArch64TTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx,
86                                       const APInt &Imm, Type *Ty,
87                                       TTI::TargetCostKind CostKind) {
88   assert(Ty->isIntegerTy());
89 
90   unsigned BitSize = Ty->getPrimitiveSizeInBits();
91   // There is no cost model for constants with a bit size of 0. Return TCC_Free
92   // here, so that constant hoisting will ignore this constant.
93   if (BitSize == 0)
94     return TTI::TCC_Free;
95 
96   unsigned ImmIdx = ~0U;
97   switch (Opcode) {
98   default:
99     return TTI::TCC_Free;
100   case Instruction::GetElementPtr:
101     // Always hoist the base address of a GetElementPtr.
102     if (Idx == 0)
103       return 2 * TTI::TCC_Basic;
104     return TTI::TCC_Free;
105   case Instruction::Store:
106     ImmIdx = 0;
107     break;
108   case Instruction::Add:
109   case Instruction::Sub:
110   case Instruction::Mul:
111   case Instruction::UDiv:
112   case Instruction::SDiv:
113   case Instruction::URem:
114   case Instruction::SRem:
115   case Instruction::And:
116   case Instruction::Or:
117   case Instruction::Xor:
118   case Instruction::ICmp:
119     ImmIdx = 1;
120     break;
121   // Always return TCC_Free for the shift value of a shift instruction.
122   case Instruction::Shl:
123   case Instruction::LShr:
124   case Instruction::AShr:
125     if (Idx == 1)
126       return TTI::TCC_Free;
127     break;
128   case Instruction::Trunc:
129   case Instruction::ZExt:
130   case Instruction::SExt:
131   case Instruction::IntToPtr:
132   case Instruction::PtrToInt:
133   case Instruction::BitCast:
134   case Instruction::PHI:
135   case Instruction::Call:
136   case Instruction::Select:
137   case Instruction::Ret:
138   case Instruction::Load:
139     break;
140   }
141 
142   if (Idx == ImmIdx) {
143     int NumConstants = (BitSize + 63) / 64;
144     int Cost = AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
145     return (Cost <= NumConstants * TTI::TCC_Basic)
146                ? static_cast<int>(TTI::TCC_Free)
147                : Cost;
148   }
149   return AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
150 }
151 
152 int AArch64TTIImpl::getIntImmCostIntrin(Intrinsic::ID IID, unsigned Idx,
153                                         const APInt &Imm, Type *Ty,
154                                         TTI::TargetCostKind CostKind) {
155   assert(Ty->isIntegerTy());
156 
157   unsigned BitSize = Ty->getPrimitiveSizeInBits();
158   // There is no cost model for constants with a bit size of 0. Return TCC_Free
159   // here, so that constant hoisting will ignore this constant.
160   if (BitSize == 0)
161     return TTI::TCC_Free;
162 
163   // Most (all?) AArch64 intrinsics do not support folding immediates into the
164   // selected instruction, so we compute the materialization cost for the
165   // immediate directly.
166   if (IID >= Intrinsic::aarch64_addg && IID <= Intrinsic::aarch64_udiv)
167     return AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
168 
169   switch (IID) {
170   default:
171     return TTI::TCC_Free;
172   case Intrinsic::sadd_with_overflow:
173   case Intrinsic::uadd_with_overflow:
174   case Intrinsic::ssub_with_overflow:
175   case Intrinsic::usub_with_overflow:
176   case Intrinsic::smul_with_overflow:
177   case Intrinsic::umul_with_overflow:
178     if (Idx == 1) {
179       int NumConstants = (BitSize + 63) / 64;
180       int Cost = AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
181       return (Cost <= NumConstants * TTI::TCC_Basic)
182                  ? static_cast<int>(TTI::TCC_Free)
183                  : Cost;
184     }
185     break;
186   case Intrinsic::experimental_stackmap:
187     if ((Idx < 2) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
188       return TTI::TCC_Free;
189     break;
190   case Intrinsic::experimental_patchpoint_void:
191   case Intrinsic::experimental_patchpoint_i64:
192     if ((Idx < 4) || (Imm.getBitWidth() <= 64 && isInt<64>(Imm.getSExtValue())))
193       return TTI::TCC_Free;
194     break;
195   }
196   return AArch64TTIImpl::getIntImmCost(Imm, Ty, CostKind);
197 }
198 
199 TargetTransformInfo::PopcntSupportKind
200 AArch64TTIImpl::getPopcntSupport(unsigned TyWidth) {
201   assert(isPowerOf2_32(TyWidth) && "Ty width must be power of 2");
202   if (TyWidth == 32 || TyWidth == 64)
203     return TTI::PSK_FastHardware;
204   // TODO: AArch64TargetLowering::LowerCTPOP() supports 128bit popcount.
205   return TTI::PSK_Software;
206 }
207 
208 bool AArch64TTIImpl::isWideningInstruction(Type *DstTy, unsigned Opcode,
209                                            ArrayRef<const Value *> Args) {
210 
211   // A helper that returns a vector type from the given type. The number of
212   // elements in type Ty determine the vector width.
213   auto toVectorTy = [&](Type *ArgTy) {
214     return FixedVectorType::get(ArgTy->getScalarType(),
215                                 cast<FixedVectorType>(DstTy)->getNumElements());
216   };
217 
218   // Exit early if DstTy is not a vector type whose elements are at least
219   // 16-bits wide.
220   if (!DstTy->isVectorTy() || DstTy->getScalarSizeInBits() < 16)
221     return false;
222 
223   // Determine if the operation has a widening variant. We consider both the
224   // "long" (e.g., usubl) and "wide" (e.g., usubw) versions of the
225   // instructions.
226   //
227   // TODO: Add additional widening operations (e.g., mul, shl, etc.) once we
228   //       verify that their extending operands are eliminated during code
229   //       generation.
230   switch (Opcode) {
231   case Instruction::Add: // UADDL(2), SADDL(2), UADDW(2), SADDW(2).
232   case Instruction::Sub: // USUBL(2), SSUBL(2), USUBW(2), SSUBW(2).
233     break;
234   default:
235     return false;
236   }
237 
238   // To be a widening instruction (either the "wide" or "long" versions), the
239   // second operand must be a sign- or zero extend having a single user. We
240   // only consider extends having a single user because they may otherwise not
241   // be eliminated.
242   if (Args.size() != 2 ||
243       (!isa<SExtInst>(Args[1]) && !isa<ZExtInst>(Args[1])) ||
244       !Args[1]->hasOneUse())
245     return false;
246   auto *Extend = cast<CastInst>(Args[1]);
247 
248   // Legalize the destination type and ensure it can be used in a widening
249   // operation.
250   auto DstTyL = TLI->getTypeLegalizationCost(DL, DstTy);
251   unsigned DstElTySize = DstTyL.second.getScalarSizeInBits();
252   if (!DstTyL.second.isVector() || DstElTySize != DstTy->getScalarSizeInBits())
253     return false;
254 
255   // Legalize the source type and ensure it can be used in a widening
256   // operation.
257   auto *SrcTy = toVectorTy(Extend->getSrcTy());
258   auto SrcTyL = TLI->getTypeLegalizationCost(DL, SrcTy);
259   unsigned SrcElTySize = SrcTyL.second.getScalarSizeInBits();
260   if (!SrcTyL.second.isVector() || SrcElTySize != SrcTy->getScalarSizeInBits())
261     return false;
262 
263   // Get the total number of vector elements in the legalized types.
264   unsigned NumDstEls = DstTyL.first * DstTyL.second.getVectorNumElements();
265   unsigned NumSrcEls = SrcTyL.first * SrcTyL.second.getVectorNumElements();
266 
267   // Return true if the legalized types have the same number of vector elements
268   // and the destination element type size is twice that of the source type.
269   return NumDstEls == NumSrcEls && 2 * SrcElTySize == DstElTySize;
270 }
271 
272 int AArch64TTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
273                                      TTI::CastContextHint CCH,
274                                      TTI::TargetCostKind CostKind,
275                                      const Instruction *I) {
276   int ISD = TLI->InstructionOpcodeToISD(Opcode);
277   assert(ISD && "Invalid opcode");
278 
279   // If the cast is observable, and it is used by a widening instruction (e.g.,
280   // uaddl, saddw, etc.), it may be free.
281   if (I && I->hasOneUse()) {
282     auto *SingleUser = cast<Instruction>(*I->user_begin());
283     SmallVector<const Value *, 4> Operands(SingleUser->operand_values());
284     if (isWideningInstruction(Dst, SingleUser->getOpcode(), Operands)) {
285       // If the cast is the second operand, it is free. We will generate either
286       // a "wide" or "long" version of the widening instruction.
287       if (I == SingleUser->getOperand(1))
288         return 0;
289       // If the cast is not the second operand, it will be free if it looks the
290       // same as the second operand. In this case, we will generate a "long"
291       // version of the widening instruction.
292       if (auto *Cast = dyn_cast<CastInst>(SingleUser->getOperand(1)))
293         if (I->getOpcode() == unsigned(Cast->getOpcode()) &&
294             cast<CastInst>(I)->getSrcTy() == Cast->getSrcTy())
295           return 0;
296     }
297   }
298 
299   // TODO: Allow non-throughput costs that aren't binary.
300   auto AdjustCost = [&CostKind](int Cost) {
301     if (CostKind != TTI::TCK_RecipThroughput)
302       return Cost == 0 ? 0 : 1;
303     return Cost;
304   };
305 
306   EVT SrcTy = TLI->getValueType(DL, Src);
307   EVT DstTy = TLI->getValueType(DL, Dst);
308 
309   if (!SrcTy.isSimple() || !DstTy.isSimple())
310     return AdjustCost(
311         BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I));
312 
313   static const TypeConversionCostTblEntry
314   ConversionTbl[] = {
315     { ISD::TRUNCATE, MVT::v4i16, MVT::v4i32,  1 },
316     { ISD::TRUNCATE, MVT::v4i32, MVT::v4i64,  0 },
317     { ISD::TRUNCATE, MVT::v8i8,  MVT::v8i32,  3 },
318     { ISD::TRUNCATE, MVT::v16i8, MVT::v16i32, 6 },
319 
320     // The number of shll instructions for the extension.
321     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i16, 3 },
322     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i16, 3 },
323     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i32, 2 },
324     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i32, 2 },
325     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i8,  3 },
326     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i8,  3 },
327     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i16, 2 },
328     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i16, 2 },
329     { ISD::SIGN_EXTEND, MVT::v8i64,  MVT::v8i8,  7 },
330     { ISD::ZERO_EXTEND, MVT::v8i64,  MVT::v8i8,  7 },
331     { ISD::SIGN_EXTEND, MVT::v8i64,  MVT::v8i16, 6 },
332     { ISD::ZERO_EXTEND, MVT::v8i64,  MVT::v8i16, 6 },
333     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 2 },
334     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 2 },
335     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
336     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
337 
338     // LowerVectorINT_TO_FP:
339     { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 },
340     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
341     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i64, 1 },
342     { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 },
343     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
344     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i64, 1 },
345 
346     // Complex: to v2f32
347     { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i8,  3 },
348     { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i16, 3 },
349     { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i64, 2 },
350     { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i8,  3 },
351     { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i16, 3 },
352     { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i64, 2 },
353 
354     // Complex: to v4f32
355     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i8,  4 },
356     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 },
357     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i8,  3 },
358     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 },
359 
360     // Complex: to v8f32
361     { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i8,  10 },
362     { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 },
363     { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i8,  10 },
364     { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 },
365 
366     // Complex: to v16f32
367     { ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i8, 21 },
368     { ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i8, 21 },
369 
370     // Complex: to v2f64
371     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i8,  4 },
372     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i16, 4 },
373     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
374     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i8,  4 },
375     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i16, 4 },
376     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
377 
378 
379     // LowerVectorFP_TO_INT
380     { ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f32, 1 },
381     { ISD::FP_TO_SINT, MVT::v4i32, MVT::v4f32, 1 },
382     { ISD::FP_TO_SINT, MVT::v2i64, MVT::v2f64, 1 },
383     { ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f32, 1 },
384     { ISD::FP_TO_UINT, MVT::v4i32, MVT::v4f32, 1 },
385     { ISD::FP_TO_UINT, MVT::v2i64, MVT::v2f64, 1 },
386 
387     // Complex, from v2f32: legal type is v2i32 (no cost) or v2i64 (1 ext).
388     { ISD::FP_TO_SINT, MVT::v2i64, MVT::v2f32, 2 },
389     { ISD::FP_TO_SINT, MVT::v2i16, MVT::v2f32, 1 },
390     { ISD::FP_TO_SINT, MVT::v2i8,  MVT::v2f32, 1 },
391     { ISD::FP_TO_UINT, MVT::v2i64, MVT::v2f32, 2 },
392     { ISD::FP_TO_UINT, MVT::v2i16, MVT::v2f32, 1 },
393     { ISD::FP_TO_UINT, MVT::v2i8,  MVT::v2f32, 1 },
394 
395     // Complex, from v4f32: legal type is v4i16, 1 narrowing => ~2
396     { ISD::FP_TO_SINT, MVT::v4i16, MVT::v4f32, 2 },
397     { ISD::FP_TO_SINT, MVT::v4i8,  MVT::v4f32, 2 },
398     { ISD::FP_TO_UINT, MVT::v4i16, MVT::v4f32, 2 },
399     { ISD::FP_TO_UINT, MVT::v4i8,  MVT::v4f32, 2 },
400 
401     // Complex, from v2f64: legal type is v2i32, 1 narrowing => ~2.
402     { ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f64, 2 },
403     { ISD::FP_TO_SINT, MVT::v2i16, MVT::v2f64, 2 },
404     { ISD::FP_TO_SINT, MVT::v2i8,  MVT::v2f64, 2 },
405     { ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f64, 2 },
406     { ISD::FP_TO_UINT, MVT::v2i16, MVT::v2f64, 2 },
407     { ISD::FP_TO_UINT, MVT::v2i8,  MVT::v2f64, 2 },
408   };
409 
410   if (const auto *Entry = ConvertCostTableLookup(ConversionTbl, ISD,
411                                                  DstTy.getSimpleVT(),
412                                                  SrcTy.getSimpleVT()))
413     return AdjustCost(Entry->Cost);
414 
415   return AdjustCost(
416       BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I));
417 }
418 
419 int AArch64TTIImpl::getExtractWithExtendCost(unsigned Opcode, Type *Dst,
420                                              VectorType *VecTy,
421                                              unsigned Index) {
422 
423   // Make sure we were given a valid extend opcode.
424   assert((Opcode == Instruction::SExt || Opcode == Instruction::ZExt) &&
425          "Invalid opcode");
426 
427   // We are extending an element we extract from a vector, so the source type
428   // of the extend is the element type of the vector.
429   auto *Src = VecTy->getElementType();
430 
431   // Sign- and zero-extends are for integer types only.
432   assert(isa<IntegerType>(Dst) && isa<IntegerType>(Src) && "Invalid type");
433 
434   // Get the cost for the extract. We compute the cost (if any) for the extend
435   // below.
436   auto Cost = getVectorInstrCost(Instruction::ExtractElement, VecTy, Index);
437 
438   // Legalize the types.
439   auto VecLT = TLI->getTypeLegalizationCost(DL, VecTy);
440   auto DstVT = TLI->getValueType(DL, Dst);
441   auto SrcVT = TLI->getValueType(DL, Src);
442   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
443 
444   // If the resulting type is still a vector and the destination type is legal,
445   // we may get the extension for free. If not, get the default cost for the
446   // extend.
447   if (!VecLT.second.isVector() || !TLI->isTypeLegal(DstVT))
448     return Cost + getCastInstrCost(Opcode, Dst, Src, TTI::CastContextHint::None,
449                                    CostKind);
450 
451   // The destination type should be larger than the element type. If not, get
452   // the default cost for the extend.
453   if (DstVT.getSizeInBits() < SrcVT.getSizeInBits())
454     return Cost + getCastInstrCost(Opcode, Dst, Src, TTI::CastContextHint::None,
455                                    CostKind);
456 
457   switch (Opcode) {
458   default:
459     llvm_unreachable("Opcode should be either SExt or ZExt");
460 
461   // For sign-extends, we only need a smov, which performs the extension
462   // automatically.
463   case Instruction::SExt:
464     return Cost;
465 
466   // For zero-extends, the extend is performed automatically by a umov unless
467   // the destination type is i64 and the element type is i8 or i16.
468   case Instruction::ZExt:
469     if (DstVT.getSizeInBits() != 64u || SrcVT.getSizeInBits() == 32u)
470       return Cost;
471   }
472 
473   // If we are unable to perform the extend for free, get the default cost.
474   return Cost + getCastInstrCost(Opcode, Dst, Src, TTI::CastContextHint::None,
475                                  CostKind);
476 }
477 
478 unsigned AArch64TTIImpl::getCFInstrCost(unsigned Opcode,
479                                         TTI::TargetCostKind CostKind) {
480   if (CostKind != TTI::TCK_RecipThroughput)
481     return Opcode == Instruction::PHI ? 0 : 1;
482   assert(CostKind == TTI::TCK_RecipThroughput && "unexpected CostKind");
483   // Branches are assumed to be predicted.
484   return 0;
485 }
486 
487 int AArch64TTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val,
488                                        unsigned Index) {
489   assert(Val->isVectorTy() && "This must be a vector type");
490 
491   if (Index != -1U) {
492     // Legalize the type.
493     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Val);
494 
495     // This type is legalized to a scalar type.
496     if (!LT.second.isVector())
497       return 0;
498 
499     // The type may be split. Normalize the index to the new type.
500     unsigned Width = LT.second.getVectorNumElements();
501     Index = Index % Width;
502 
503     // The element at index zero is already inside the vector.
504     if (Index == 0)
505       return 0;
506   }
507 
508   // All other insert/extracts cost this much.
509   return ST->getVectorInsertExtractBaseCost();
510 }
511 
512 int AArch64TTIImpl::getArithmeticInstrCost(
513     unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
514     TTI::OperandValueKind Opd1Info,
515     TTI::OperandValueKind Opd2Info, TTI::OperandValueProperties Opd1PropInfo,
516     TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args,
517     const Instruction *CxtI) {
518   // TODO: Handle more cost kinds.
519   if (CostKind != TTI::TCK_RecipThroughput)
520     return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info,
521                                          Opd2Info, Opd1PropInfo,
522                                          Opd2PropInfo, Args, CxtI);
523 
524   // Legalize the type.
525   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
526 
527   // If the instruction is a widening instruction (e.g., uaddl, saddw, etc.),
528   // add in the widening overhead specified by the sub-target. Since the
529   // extends feeding widening instructions are performed automatically, they
530   // aren't present in the generated code and have a zero cost. By adding a
531   // widening overhead here, we attach the total cost of the combined operation
532   // to the widening instruction.
533   int Cost = 0;
534   if (isWideningInstruction(Ty, Opcode, Args))
535     Cost += ST->getWideningBaseCost();
536 
537   int ISD = TLI->InstructionOpcodeToISD(Opcode);
538 
539   switch (ISD) {
540   default:
541     return Cost + BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info,
542                                                 Opd2Info,
543                                                 Opd1PropInfo, Opd2PropInfo);
544   case ISD::SDIV:
545     if (Opd2Info == TargetTransformInfo::OK_UniformConstantValue &&
546         Opd2PropInfo == TargetTransformInfo::OP_PowerOf2) {
547       // On AArch64, scalar signed division by constants power-of-two are
548       // normally expanded to the sequence ADD + CMP + SELECT + SRA.
549       // The OperandValue properties many not be same as that of previous
550       // operation; conservatively assume OP_None.
551       Cost += getArithmeticInstrCost(Instruction::Add, Ty, CostKind,
552                                      Opd1Info, Opd2Info,
553                                      TargetTransformInfo::OP_None,
554                                      TargetTransformInfo::OP_None);
555       Cost += getArithmeticInstrCost(Instruction::Sub, Ty, CostKind,
556                                      Opd1Info, Opd2Info,
557                                      TargetTransformInfo::OP_None,
558                                      TargetTransformInfo::OP_None);
559       Cost += getArithmeticInstrCost(Instruction::Select, Ty, CostKind,
560                                      Opd1Info, Opd2Info,
561                                      TargetTransformInfo::OP_None,
562                                      TargetTransformInfo::OP_None);
563       Cost += getArithmeticInstrCost(Instruction::AShr, Ty, CostKind,
564                                      Opd1Info, Opd2Info,
565                                      TargetTransformInfo::OP_None,
566                                      TargetTransformInfo::OP_None);
567       return Cost;
568     }
569     LLVM_FALLTHROUGH;
570   case ISD::UDIV:
571     if (Opd2Info == TargetTransformInfo::OK_UniformConstantValue) {
572       auto VT = TLI->getValueType(DL, Ty);
573       if (TLI->isOperationLegalOrCustom(ISD::MULHU, VT)) {
574         // Vector signed division by constant are expanded to the
575         // sequence MULHS + ADD/SUB + SRA + SRL + ADD, and unsigned division
576         // to MULHS + SUB + SRL + ADD + SRL.
577         int MulCost = getArithmeticInstrCost(Instruction::Mul, Ty, CostKind,
578                                              Opd1Info, Opd2Info,
579                                              TargetTransformInfo::OP_None,
580                                              TargetTransformInfo::OP_None);
581         int AddCost = getArithmeticInstrCost(Instruction::Add, Ty, CostKind,
582                                              Opd1Info, Opd2Info,
583                                              TargetTransformInfo::OP_None,
584                                              TargetTransformInfo::OP_None);
585         int ShrCost = getArithmeticInstrCost(Instruction::AShr, Ty, CostKind,
586                                              Opd1Info, Opd2Info,
587                                              TargetTransformInfo::OP_None,
588                                              TargetTransformInfo::OP_None);
589         return MulCost * 2 + AddCost * 2 + ShrCost * 2 + 1;
590       }
591     }
592 
593     Cost += BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info,
594                                           Opd2Info,
595                                           Opd1PropInfo, Opd2PropInfo);
596     if (Ty->isVectorTy()) {
597       // On AArch64, vector divisions are not supported natively and are
598       // expanded into scalar divisions of each pair of elements.
599       Cost += getArithmeticInstrCost(Instruction::ExtractElement, Ty, CostKind,
600                                      Opd1Info, Opd2Info, Opd1PropInfo,
601                                      Opd2PropInfo);
602       Cost += getArithmeticInstrCost(Instruction::InsertElement, Ty, CostKind,
603                                      Opd1Info, Opd2Info, Opd1PropInfo,
604                                      Opd2PropInfo);
605       // TODO: if one of the arguments is scalar, then it's not necessary to
606       // double the cost of handling the vector elements.
607       Cost += Cost;
608     }
609     return Cost;
610 
611   case ISD::ADD:
612   case ISD::MUL:
613   case ISD::XOR:
614   case ISD::OR:
615   case ISD::AND:
616     // These nodes are marked as 'custom' for combining purposes only.
617     // We know that they are legal. See LowerAdd in ISelLowering.
618     return (Cost + 1) * LT.first;
619 
620   case ISD::FADD:
621     // These nodes are marked as 'custom' just to lower them to SVE.
622     // We know said lowering will incur no additional cost.
623     if (isa<FixedVectorType>(Ty) && !Ty->getScalarType()->isFP128Ty())
624       return (Cost + 2) * LT.first;
625 
626     return Cost + BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info,
627                                                 Opd2Info,
628                                                 Opd1PropInfo, Opd2PropInfo);
629   }
630 }
631 
632 int AArch64TTIImpl::getAddressComputationCost(Type *Ty, ScalarEvolution *SE,
633                                               const SCEV *Ptr) {
634   // Address computations in vectorized code with non-consecutive addresses will
635   // likely result in more instructions compared to scalar code where the
636   // computation can more often be merged into the index mode. The resulting
637   // extra micro-ops can significantly decrease throughput.
638   unsigned NumVectorInstToHideOverhead = 10;
639   int MaxMergeDistance = 64;
640 
641   if (Ty->isVectorTy() && SE &&
642       !BaseT::isConstantStridedAccessLessThan(SE, Ptr, MaxMergeDistance + 1))
643     return NumVectorInstToHideOverhead;
644 
645   // In many cases the address computation is not merged into the instruction
646   // addressing mode.
647   return 1;
648 }
649 
650 int AArch64TTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
651                                        Type *CondTy,
652                                        TTI::TargetCostKind CostKind,
653                                        const Instruction *I) {
654   // TODO: Handle other cost kinds.
655   if (CostKind != TTI::TCK_RecipThroughput)
656     return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, CostKind, I);
657 
658   int ISD = TLI->InstructionOpcodeToISD(Opcode);
659   // We don't lower some vector selects well that are wider than the register
660   // width.
661   if (ValTy->isVectorTy() && ISD == ISD::SELECT) {
662     // We would need this many instructions to hide the scalarization happening.
663     const int AmortizationCost = 20;
664     static const TypeConversionCostTblEntry
665     VectorSelectTbl[] = {
666       { ISD::SELECT, MVT::v16i1, MVT::v16i16, 16 },
667       { ISD::SELECT, MVT::v8i1, MVT::v8i32, 8 },
668       { ISD::SELECT, MVT::v16i1, MVT::v16i32, 16 },
669       { ISD::SELECT, MVT::v4i1, MVT::v4i64, 4 * AmortizationCost },
670       { ISD::SELECT, MVT::v8i1, MVT::v8i64, 8 * AmortizationCost },
671       { ISD::SELECT, MVT::v16i1, MVT::v16i64, 16 * AmortizationCost }
672     };
673 
674     EVT SelCondTy = TLI->getValueType(DL, CondTy);
675     EVT SelValTy = TLI->getValueType(DL, ValTy);
676     if (SelCondTy.isSimple() && SelValTy.isSimple()) {
677       if (const auto *Entry = ConvertCostTableLookup(VectorSelectTbl, ISD,
678                                                      SelCondTy.getSimpleVT(),
679                                                      SelValTy.getSimpleVT()))
680         return Entry->Cost;
681     }
682   }
683   return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, CostKind, I);
684 }
685 
686 AArch64TTIImpl::TTI::MemCmpExpansionOptions
687 AArch64TTIImpl::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const {
688   TTI::MemCmpExpansionOptions Options;
689   if (ST->requiresStrictAlign()) {
690     // TODO: Add cost modeling for strict align. Misaligned loads expand to
691     // a bunch of instructions when strict align is enabled.
692     return Options;
693   }
694   Options.AllowOverlappingLoads = true;
695   Options.MaxNumLoads = TLI->getMaxExpandSizeMemcmp(OptSize);
696   Options.NumLoadsPerBlock = Options.MaxNumLoads;
697   // TODO: Though vector loads usually perform well on AArch64, in some targets
698   // they may wake up the FP unit, which raises the power consumption.  Perhaps
699   // they could be used with no holds barred (-O3).
700   Options.LoadSizes = {8, 4, 2, 1};
701   return Options;
702 }
703 
704 int AArch64TTIImpl::getMemoryOpCost(unsigned Opcode, Type *Ty,
705                                     MaybeAlign Alignment, unsigned AddressSpace,
706                                     TTI::TargetCostKind CostKind,
707                                     const Instruction *I) {
708   // TODO: Handle other cost kinds.
709   if (CostKind != TTI::TCK_RecipThroughput)
710     return 1;
711 
712   // Type legalization can't handle structs
713   if (TLI->getValueType(DL, Ty,  true) == MVT::Other)
714     return BaseT::getMemoryOpCost(Opcode, Ty, Alignment, AddressSpace,
715                                   CostKind);
716 
717   auto LT = TLI->getTypeLegalizationCost(DL, Ty);
718 
719   if (ST->isMisaligned128StoreSlow() && Opcode == Instruction::Store &&
720       LT.second.is128BitVector() && (!Alignment || *Alignment < Align(16))) {
721     // Unaligned stores are extremely inefficient. We don't split all
722     // unaligned 128-bit stores because the negative impact that has shown in
723     // practice on inlined block copy code.
724     // We make such stores expensive so that we will only vectorize if there
725     // are 6 other instructions getting vectorized.
726     const int AmortizationCost = 6;
727 
728     return LT.first * 2 * AmortizationCost;
729   }
730 
731   if (Ty->isVectorTy() &&
732       cast<VectorType>(Ty)->getElementType()->isIntegerTy(8)) {
733     unsigned ProfitableNumElements;
734     if (Opcode == Instruction::Store)
735       // We use a custom trunc store lowering so v.4b should be profitable.
736       ProfitableNumElements = 4;
737     else
738       // We scalarize the loads because there is not v.4b register and we
739       // have to promote the elements to v.2.
740       ProfitableNumElements = 8;
741 
742     if (cast<FixedVectorType>(Ty)->getNumElements() < ProfitableNumElements) {
743       unsigned NumVecElts = cast<FixedVectorType>(Ty)->getNumElements();
744       unsigned NumVectorizableInstsToAmortize = NumVecElts * 2;
745       // We generate 2 instructions per vector element.
746       return NumVectorizableInstsToAmortize * NumVecElts * 2;
747     }
748   }
749 
750   return LT.first;
751 }
752 
753 int AArch64TTIImpl::getInterleavedMemoryOpCost(
754     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
755     Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
756     bool UseMaskForCond, bool UseMaskForGaps) {
757   assert(Factor >= 2 && "Invalid interleave factor");
758   auto *VecVTy = cast<FixedVectorType>(VecTy);
759 
760   if (!UseMaskForCond && !UseMaskForGaps &&
761       Factor <= TLI->getMaxSupportedInterleaveFactor()) {
762     unsigned NumElts = VecVTy->getNumElements();
763     auto *SubVecTy =
764         FixedVectorType::get(VecTy->getScalarType(), NumElts / Factor);
765 
766     // ldN/stN only support legal vector types of size 64 or 128 in bits.
767     // Accesses having vector types that are a multiple of 128 bits can be
768     // matched to more than one ldN/stN instruction.
769     if (NumElts % Factor == 0 &&
770         TLI->isLegalInterleavedAccessType(SubVecTy, DL))
771       return Factor * TLI->getNumInterleavedAccesses(SubVecTy, DL);
772   }
773 
774   return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
775                                            Alignment, AddressSpace, CostKind,
776                                            UseMaskForCond, UseMaskForGaps);
777 }
778 
779 int AArch64TTIImpl::getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) {
780   int Cost = 0;
781   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
782   for (auto *I : Tys) {
783     if (!I->isVectorTy())
784       continue;
785     if (I->getScalarSizeInBits() * cast<FixedVectorType>(I)->getNumElements() ==
786         128)
787       Cost += getMemoryOpCost(Instruction::Store, I, Align(128), 0, CostKind) +
788               getMemoryOpCost(Instruction::Load, I, Align(128), 0, CostKind);
789   }
790   return Cost;
791 }
792 
793 unsigned AArch64TTIImpl::getMaxInterleaveFactor(unsigned VF) {
794   return ST->getMaxInterleaveFactor();
795 }
796 
797 // For Falkor, we want to avoid having too many strided loads in a loop since
798 // that can exhaust the HW prefetcher resources.  We adjust the unroller
799 // MaxCount preference below to attempt to ensure unrolling doesn't create too
800 // many strided loads.
801 static void
802 getFalkorUnrollingPreferences(Loop *L, ScalarEvolution &SE,
803                               TargetTransformInfo::UnrollingPreferences &UP) {
804   enum { MaxStridedLoads = 7 };
805   auto countStridedLoads = [](Loop *L, ScalarEvolution &SE) {
806     int StridedLoads = 0;
807     // FIXME? We could make this more precise by looking at the CFG and
808     // e.g. not counting loads in each side of an if-then-else diamond.
809     for (const auto BB : L->blocks()) {
810       for (auto &I : *BB) {
811         LoadInst *LMemI = dyn_cast<LoadInst>(&I);
812         if (!LMemI)
813           continue;
814 
815         Value *PtrValue = LMemI->getPointerOperand();
816         if (L->isLoopInvariant(PtrValue))
817           continue;
818 
819         const SCEV *LSCEV = SE.getSCEV(PtrValue);
820         const SCEVAddRecExpr *LSCEVAddRec = dyn_cast<SCEVAddRecExpr>(LSCEV);
821         if (!LSCEVAddRec || !LSCEVAddRec->isAffine())
822           continue;
823 
824         // FIXME? We could take pairing of unrolled load copies into account
825         // by looking at the AddRec, but we would probably have to limit this
826         // to loops with no stores or other memory optimization barriers.
827         ++StridedLoads;
828         // We've seen enough strided loads that seeing more won't make a
829         // difference.
830         if (StridedLoads > MaxStridedLoads / 2)
831           return StridedLoads;
832       }
833     }
834     return StridedLoads;
835   };
836 
837   int StridedLoads = countStridedLoads(L, SE);
838   LLVM_DEBUG(dbgs() << "falkor-hwpf: detected " << StridedLoads
839                     << " strided loads\n");
840   // Pick the largest power of 2 unroll count that won't result in too many
841   // strided loads.
842   if (StridedLoads) {
843     UP.MaxCount = 1 << Log2_32(MaxStridedLoads / StridedLoads);
844     LLVM_DEBUG(dbgs() << "falkor-hwpf: setting unroll MaxCount to "
845                       << UP.MaxCount << '\n');
846   }
847 }
848 
849 void AArch64TTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
850                                              TTI::UnrollingPreferences &UP) {
851   // Enable partial unrolling and runtime unrolling.
852   BaseT::getUnrollingPreferences(L, SE, UP);
853 
854   // For inner loop, it is more likely to be a hot one, and the runtime check
855   // can be promoted out from LICM pass, so the overhead is less, let's try
856   // a larger threshold to unroll more loops.
857   if (L->getLoopDepth() > 1)
858     UP.PartialThreshold *= 2;
859 
860   // Disable partial & runtime unrolling on -Os.
861   UP.PartialOptSizeThreshold = 0;
862 
863   if (ST->getProcFamily() == AArch64Subtarget::Falkor &&
864       EnableFalkorHWPFUnrollFix)
865     getFalkorUnrollingPreferences(L, SE, UP);
866 }
867 
868 void AArch64TTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
869                                            TTI::PeelingPreferences &PP) {
870   BaseT::getPeelingPreferences(L, SE, PP);
871 }
872 
873 Value *AArch64TTIImpl::getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
874                                                          Type *ExpectedType) {
875   switch (Inst->getIntrinsicID()) {
876   default:
877     return nullptr;
878   case Intrinsic::aarch64_neon_st2:
879   case Intrinsic::aarch64_neon_st3:
880   case Intrinsic::aarch64_neon_st4: {
881     // Create a struct type
882     StructType *ST = dyn_cast<StructType>(ExpectedType);
883     if (!ST)
884       return nullptr;
885     unsigned NumElts = Inst->getNumArgOperands() - 1;
886     if (ST->getNumElements() != NumElts)
887       return nullptr;
888     for (unsigned i = 0, e = NumElts; i != e; ++i) {
889       if (Inst->getArgOperand(i)->getType() != ST->getElementType(i))
890         return nullptr;
891     }
892     Value *Res = UndefValue::get(ExpectedType);
893     IRBuilder<> Builder(Inst);
894     for (unsigned i = 0, e = NumElts; i != e; ++i) {
895       Value *L = Inst->getArgOperand(i);
896       Res = Builder.CreateInsertValue(Res, L, i);
897     }
898     return Res;
899   }
900   case Intrinsic::aarch64_neon_ld2:
901   case Intrinsic::aarch64_neon_ld3:
902   case Intrinsic::aarch64_neon_ld4:
903     if (Inst->getType() == ExpectedType)
904       return Inst;
905     return nullptr;
906   }
907 }
908 
909 bool AArch64TTIImpl::getTgtMemIntrinsic(IntrinsicInst *Inst,
910                                         MemIntrinsicInfo &Info) {
911   switch (Inst->getIntrinsicID()) {
912   default:
913     break;
914   case Intrinsic::aarch64_neon_ld2:
915   case Intrinsic::aarch64_neon_ld3:
916   case Intrinsic::aarch64_neon_ld4:
917     Info.ReadMem = true;
918     Info.WriteMem = false;
919     Info.PtrVal = Inst->getArgOperand(0);
920     break;
921   case Intrinsic::aarch64_neon_st2:
922   case Intrinsic::aarch64_neon_st3:
923   case Intrinsic::aarch64_neon_st4:
924     Info.ReadMem = false;
925     Info.WriteMem = true;
926     Info.PtrVal = Inst->getArgOperand(Inst->getNumArgOperands() - 1);
927     break;
928   }
929 
930   switch (Inst->getIntrinsicID()) {
931   default:
932     return false;
933   case Intrinsic::aarch64_neon_ld2:
934   case Intrinsic::aarch64_neon_st2:
935     Info.MatchingId = VECTOR_LDST_TWO_ELEMENTS;
936     break;
937   case Intrinsic::aarch64_neon_ld3:
938   case Intrinsic::aarch64_neon_st3:
939     Info.MatchingId = VECTOR_LDST_THREE_ELEMENTS;
940     break;
941   case Intrinsic::aarch64_neon_ld4:
942   case Intrinsic::aarch64_neon_st4:
943     Info.MatchingId = VECTOR_LDST_FOUR_ELEMENTS;
944     break;
945   }
946   return true;
947 }
948 
949 /// See if \p I should be considered for address type promotion. We check if \p
950 /// I is a sext with right type and used in memory accesses. If it used in a
951 /// "complex" getelementptr, we allow it to be promoted without finding other
952 /// sext instructions that sign extended the same initial value. A getelementptr
953 /// is considered as "complex" if it has more than 2 operands.
954 bool AArch64TTIImpl::shouldConsiderAddressTypePromotion(
955     const Instruction &I, bool &AllowPromotionWithoutCommonHeader) {
956   bool Considerable = false;
957   AllowPromotionWithoutCommonHeader = false;
958   if (!isa<SExtInst>(&I))
959     return false;
960   Type *ConsideredSExtType =
961       Type::getInt64Ty(I.getParent()->getParent()->getContext());
962   if (I.getType() != ConsideredSExtType)
963     return false;
964   // See if the sext is the one with the right type and used in at least one
965   // GetElementPtrInst.
966   for (const User *U : I.users()) {
967     if (const GetElementPtrInst *GEPInst = dyn_cast<GetElementPtrInst>(U)) {
968       Considerable = true;
969       // A getelementptr is considered as "complex" if it has more than 2
970       // operands. We will promote a SExt used in such complex GEP as we
971       // expect some computation to be merged if they are done on 64 bits.
972       if (GEPInst->getNumOperands() > 2) {
973         AllowPromotionWithoutCommonHeader = true;
974         break;
975       }
976     }
977   }
978   return Considerable;
979 }
980 
981 bool AArch64TTIImpl::useReductionIntrinsic(unsigned Opcode, Type *Ty,
982                                            TTI::ReductionFlags Flags) const {
983   auto *VTy = cast<VectorType>(Ty);
984   unsigned ScalarBits = Ty->getScalarSizeInBits();
985   switch (Opcode) {
986   case Instruction::FAdd:
987   case Instruction::FMul:
988   case Instruction::And:
989   case Instruction::Or:
990   case Instruction::Xor:
991   case Instruction::Mul:
992     return false;
993   case Instruction::Add:
994     return ScalarBits * cast<FixedVectorType>(VTy)->getNumElements() >= 128;
995   case Instruction::ICmp:
996     return (ScalarBits < 64) &&
997            (ScalarBits * cast<FixedVectorType>(VTy)->getNumElements() >= 128);
998   case Instruction::FCmp:
999     return Flags.NoNaN;
1000   default:
1001     llvm_unreachable("Unhandled reduction opcode");
1002   }
1003   return false;
1004 }
1005 
1006 int AArch64TTIImpl::getArithmeticReductionCost(unsigned Opcode,
1007                                                VectorType *ValTy,
1008                                                bool IsPairwiseForm,
1009                                                TTI::TargetCostKind CostKind) {
1010 
1011   if (IsPairwiseForm)
1012     return BaseT::getArithmeticReductionCost(Opcode, ValTy, IsPairwiseForm,
1013                                              CostKind);
1014 
1015   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
1016   MVT MTy = LT.second;
1017   int ISD = TLI->InstructionOpcodeToISD(Opcode);
1018   assert(ISD && "Invalid opcode");
1019 
1020   // Horizontal adds can use the 'addv' instruction. We model the cost of these
1021   // instructions as normal vector adds. This is the only arithmetic vector
1022   // reduction operation for which we have an instruction.
1023   static const CostTblEntry CostTblNoPairwise[]{
1024       {ISD::ADD, MVT::v8i8,  1},
1025       {ISD::ADD, MVT::v16i8, 1},
1026       {ISD::ADD, MVT::v4i16, 1},
1027       {ISD::ADD, MVT::v8i16, 1},
1028       {ISD::ADD, MVT::v4i32, 1},
1029   };
1030 
1031   if (const auto *Entry = CostTableLookup(CostTblNoPairwise, ISD, MTy))
1032     return LT.first * Entry->Cost;
1033 
1034   return BaseT::getArithmeticReductionCost(Opcode, ValTy, IsPairwiseForm,
1035                                            CostKind);
1036 }
1037 
1038 int AArch64TTIImpl::getShuffleCost(TTI::ShuffleKind Kind, VectorType *Tp,
1039                                    int Index, VectorType *SubTp) {
1040   if (Kind == TTI::SK_Broadcast || Kind == TTI::SK_Transpose ||
1041       Kind == TTI::SK_Select || Kind == TTI::SK_PermuteSingleSrc) {
1042     static const CostTblEntry ShuffleTbl[] = {
1043       // Broadcast shuffle kinds can be performed with 'dup'.
1044       { TTI::SK_Broadcast, MVT::v8i8,  1 },
1045       { TTI::SK_Broadcast, MVT::v16i8, 1 },
1046       { TTI::SK_Broadcast, MVT::v4i16, 1 },
1047       { TTI::SK_Broadcast, MVT::v8i16, 1 },
1048       { TTI::SK_Broadcast, MVT::v2i32, 1 },
1049       { TTI::SK_Broadcast, MVT::v4i32, 1 },
1050       { TTI::SK_Broadcast, MVT::v2i64, 1 },
1051       { TTI::SK_Broadcast, MVT::v2f32, 1 },
1052       { TTI::SK_Broadcast, MVT::v4f32, 1 },
1053       { TTI::SK_Broadcast, MVT::v2f64, 1 },
1054       // Transpose shuffle kinds can be performed with 'trn1/trn2' and
1055       // 'zip1/zip2' instructions.
1056       { TTI::SK_Transpose, MVT::v8i8,  1 },
1057       { TTI::SK_Transpose, MVT::v16i8, 1 },
1058       { TTI::SK_Transpose, MVT::v4i16, 1 },
1059       { TTI::SK_Transpose, MVT::v8i16, 1 },
1060       { TTI::SK_Transpose, MVT::v2i32, 1 },
1061       { TTI::SK_Transpose, MVT::v4i32, 1 },
1062       { TTI::SK_Transpose, MVT::v2i64, 1 },
1063       { TTI::SK_Transpose, MVT::v2f32, 1 },
1064       { TTI::SK_Transpose, MVT::v4f32, 1 },
1065       { TTI::SK_Transpose, MVT::v2f64, 1 },
1066       // Select shuffle kinds.
1067       // TODO: handle vXi8/vXi16.
1068       { TTI::SK_Select, MVT::v2i32, 1 }, // mov.
1069       { TTI::SK_Select, MVT::v4i32, 2 }, // rev+trn (or similar).
1070       { TTI::SK_Select, MVT::v2i64, 1 }, // mov.
1071       { TTI::SK_Select, MVT::v2f32, 1 }, // mov.
1072       { TTI::SK_Select, MVT::v4f32, 2 }, // rev+trn (or similar).
1073       { TTI::SK_Select, MVT::v2f64, 1 }, // mov.
1074       // PermuteSingleSrc shuffle kinds.
1075       // TODO: handle vXi8/vXi16.
1076       { TTI::SK_PermuteSingleSrc, MVT::v2i32, 1 }, // mov.
1077       { TTI::SK_PermuteSingleSrc, MVT::v4i32, 3 }, // perfectshuffle worst case.
1078       { TTI::SK_PermuteSingleSrc, MVT::v2i64, 1 }, // mov.
1079       { TTI::SK_PermuteSingleSrc, MVT::v2f32, 1 }, // mov.
1080       { TTI::SK_PermuteSingleSrc, MVT::v4f32, 3 }, // perfectshuffle worst case.
1081       { TTI::SK_PermuteSingleSrc, MVT::v2f64, 1 }, // mov.
1082     };
1083     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
1084     if (const auto *Entry = CostTableLookup(ShuffleTbl, Kind, LT.second))
1085       return LT.first * Entry->Cost;
1086   }
1087 
1088   return BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
1089 }
1090