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