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