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   case Intrinsic::sadd_sat:
239   case Intrinsic::ssub_sat:
240   case Intrinsic::uadd_sat:
241   case Intrinsic::usub_sat: {
242     static const auto ValidSatTys = {MVT::v8i8,  MVT::v16i8, MVT::v4i16,
243                                      MVT::v8i16, MVT::v2i32, MVT::v4i32,
244                                      MVT::v2i64};
245     auto LT = TLI->getTypeLegalizationCost(DL, RetTy);
246     // This is a base cost of 1 for the vadd, plus 3 extract shifts if we
247     // need to extend the type, as it uses shr(qadd(shl, shl)).
248     unsigned Instrs =
249         LT.second.getScalarSizeInBits() == RetTy->getScalarSizeInBits() ? 1 : 4;
250     if (any_of(ValidSatTys, [&LT](MVT M) { return M == LT.second; }))
251       return LT.first * Instrs;
252     break;
253   }
254   case Intrinsic::abs: {
255     static const auto ValidAbsTys = {MVT::v8i8,  MVT::v16i8, MVT::v4i16,
256                                      MVT::v8i16, MVT::v2i32, MVT::v4i32,
257                                      MVT::v2i64};
258     auto LT = TLI->getTypeLegalizationCost(DL, RetTy);
259     if (any_of(ValidAbsTys, [&LT](MVT M) { return M == LT.second; }))
260       return LT.first;
261     break;
262   }
263   case Intrinsic::experimental_stepvector: {
264     unsigned Cost = 1; // Cost of the `index' instruction
265     auto LT = TLI->getTypeLegalizationCost(DL, RetTy);
266     // Legalisation of illegal vectors involves an `index' instruction plus
267     // (LT.first - 1) vector adds.
268     if (LT.first > 1) {
269       Type *LegalVTy = EVT(LT.second).getTypeForEVT(RetTy->getContext());
270       unsigned AddCost =
271           getArithmeticInstrCost(Instruction::Add, LegalVTy, CostKind);
272       Cost += AddCost * (LT.first - 1);
273     }
274     return Cost;
275   }
276   default:
277     break;
278   }
279   return BaseT::getIntrinsicInstrCost(ICA, CostKind);
280 }
281 
282 bool AArch64TTIImpl::isWideningInstruction(Type *DstTy, unsigned Opcode,
283                                            ArrayRef<const Value *> Args) {
284 
285   // A helper that returns a vector type from the given type. The number of
286   // elements in type Ty determine the vector width.
287   auto toVectorTy = [&](Type *ArgTy) {
288     return VectorType::get(ArgTy->getScalarType(),
289                            cast<VectorType>(DstTy)->getElementCount());
290   };
291 
292   // Exit early if DstTy is not a vector type whose elements are at least
293   // 16-bits wide.
294   if (!DstTy->isVectorTy() || DstTy->getScalarSizeInBits() < 16)
295     return false;
296 
297   // Determine if the operation has a widening variant. We consider both the
298   // "long" (e.g., usubl) and "wide" (e.g., usubw) versions of the
299   // instructions.
300   //
301   // TODO: Add additional widening operations (e.g., mul, shl, etc.) once we
302   //       verify that their extending operands are eliminated during code
303   //       generation.
304   switch (Opcode) {
305   case Instruction::Add: // UADDL(2), SADDL(2), UADDW(2), SADDW(2).
306   case Instruction::Sub: // USUBL(2), SSUBL(2), USUBW(2), SSUBW(2).
307     break;
308   default:
309     return false;
310   }
311 
312   // To be a widening instruction (either the "wide" or "long" versions), the
313   // second operand must be a sign- or zero extend having a single user. We
314   // only consider extends having a single user because they may otherwise not
315   // be eliminated.
316   if (Args.size() != 2 ||
317       (!isa<SExtInst>(Args[1]) && !isa<ZExtInst>(Args[1])) ||
318       !Args[1]->hasOneUse())
319     return false;
320   auto *Extend = cast<CastInst>(Args[1]);
321 
322   // Legalize the destination type and ensure it can be used in a widening
323   // operation.
324   auto DstTyL = TLI->getTypeLegalizationCost(DL, DstTy);
325   unsigned DstElTySize = DstTyL.second.getScalarSizeInBits();
326   if (!DstTyL.second.isVector() || DstElTySize != DstTy->getScalarSizeInBits())
327     return false;
328 
329   // Legalize the source type and ensure it can be used in a widening
330   // operation.
331   auto *SrcTy = toVectorTy(Extend->getSrcTy());
332   auto SrcTyL = TLI->getTypeLegalizationCost(DL, SrcTy);
333   unsigned SrcElTySize = SrcTyL.second.getScalarSizeInBits();
334   if (!SrcTyL.second.isVector() || SrcElTySize != SrcTy->getScalarSizeInBits())
335     return false;
336 
337   // Get the total number of vector elements in the legalized types.
338   unsigned NumDstEls = DstTyL.first * DstTyL.second.getVectorMinNumElements();
339   unsigned NumSrcEls = SrcTyL.first * SrcTyL.second.getVectorMinNumElements();
340 
341   // Return true if the legalized types have the same number of vector elements
342   // and the destination element type size is twice that of the source type.
343   return NumDstEls == NumSrcEls && 2 * SrcElTySize == DstElTySize;
344 }
345 
346 int AArch64TTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
347                                      TTI::CastContextHint CCH,
348                                      TTI::TargetCostKind CostKind,
349                                      const Instruction *I) {
350   int ISD = TLI->InstructionOpcodeToISD(Opcode);
351   assert(ISD && "Invalid opcode");
352 
353   // If the cast is observable, and it is used by a widening instruction (e.g.,
354   // uaddl, saddw, etc.), it may be free.
355   if (I && I->hasOneUse()) {
356     auto *SingleUser = cast<Instruction>(*I->user_begin());
357     SmallVector<const Value *, 4> Operands(SingleUser->operand_values());
358     if (isWideningInstruction(Dst, SingleUser->getOpcode(), Operands)) {
359       // If the cast is the second operand, it is free. We will generate either
360       // a "wide" or "long" version of the widening instruction.
361       if (I == SingleUser->getOperand(1))
362         return 0;
363       // If the cast is not the second operand, it will be free if it looks the
364       // same as the second operand. In this case, we will generate a "long"
365       // version of the widening instruction.
366       if (auto *Cast = dyn_cast<CastInst>(SingleUser->getOperand(1)))
367         if (I->getOpcode() == unsigned(Cast->getOpcode()) &&
368             cast<CastInst>(I)->getSrcTy() == Cast->getSrcTy())
369           return 0;
370     }
371   }
372 
373   // TODO: Allow non-throughput costs that aren't binary.
374   auto AdjustCost = [&CostKind](int Cost) {
375     if (CostKind != TTI::TCK_RecipThroughput)
376       return Cost == 0 ? 0 : 1;
377     return Cost;
378   };
379 
380   EVT SrcTy = TLI->getValueType(DL, Src);
381   EVT DstTy = TLI->getValueType(DL, Dst);
382 
383   if (!SrcTy.isSimple() || !DstTy.isSimple())
384     return AdjustCost(
385         BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I));
386 
387   static const TypeConversionCostTblEntry
388   ConversionTbl[] = {
389     { ISD::TRUNCATE, MVT::v4i16, MVT::v4i32,  1 },
390     { ISD::TRUNCATE, MVT::v4i32, MVT::v4i64,  0 },
391     { ISD::TRUNCATE, MVT::v8i8,  MVT::v8i32,  3 },
392     { ISD::TRUNCATE, MVT::v16i8, MVT::v16i32, 6 },
393 
394     // The number of shll instructions for the extension.
395     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i16, 3 },
396     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i16, 3 },
397     { ISD::SIGN_EXTEND, MVT::v4i64,  MVT::v4i32, 2 },
398     { ISD::ZERO_EXTEND, MVT::v4i64,  MVT::v4i32, 2 },
399     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i8,  3 },
400     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i8,  3 },
401     { ISD::SIGN_EXTEND, MVT::v8i32,  MVT::v8i16, 2 },
402     { ISD::ZERO_EXTEND, MVT::v8i32,  MVT::v8i16, 2 },
403     { ISD::SIGN_EXTEND, MVT::v8i64,  MVT::v8i8,  7 },
404     { ISD::ZERO_EXTEND, MVT::v8i64,  MVT::v8i8,  7 },
405     { ISD::SIGN_EXTEND, MVT::v8i64,  MVT::v8i16, 6 },
406     { ISD::ZERO_EXTEND, MVT::v8i64,  MVT::v8i16, 6 },
407     { ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 2 },
408     { ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 2 },
409     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
410     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
411 
412     // LowerVectorINT_TO_FP:
413     { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 },
414     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
415     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i64, 1 },
416     { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i32, 1 },
417     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i32, 1 },
418     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i64, 1 },
419 
420     // Complex: to v2f32
421     { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i8,  3 },
422     { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i16, 3 },
423     { ISD::SINT_TO_FP, MVT::v2f32, MVT::v2i64, 2 },
424     { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i8,  3 },
425     { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i16, 3 },
426     { ISD::UINT_TO_FP, MVT::v2f32, MVT::v2i64, 2 },
427 
428     // Complex: to v4f32
429     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i8,  4 },
430     { ISD::SINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 },
431     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i8,  3 },
432     { ISD::UINT_TO_FP, MVT::v4f32, MVT::v4i16, 2 },
433 
434     // Complex: to v8f32
435     { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i8,  10 },
436     { ISD::SINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 },
437     { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i8,  10 },
438     { ISD::UINT_TO_FP, MVT::v8f32, MVT::v8i16, 4 },
439 
440     // Complex: to v16f32
441     { ISD::SINT_TO_FP, MVT::v16f32, MVT::v16i8, 21 },
442     { ISD::UINT_TO_FP, MVT::v16f32, MVT::v16i8, 21 },
443 
444     // Complex: to v2f64
445     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i8,  4 },
446     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i16, 4 },
447     { ISD::SINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
448     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i8,  4 },
449     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i16, 4 },
450     { ISD::UINT_TO_FP, MVT::v2f64, MVT::v2i32, 2 },
451 
452 
453     // LowerVectorFP_TO_INT
454     { ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f32, 1 },
455     { ISD::FP_TO_SINT, MVT::v4i32, MVT::v4f32, 1 },
456     { ISD::FP_TO_SINT, MVT::v2i64, MVT::v2f64, 1 },
457     { ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f32, 1 },
458     { ISD::FP_TO_UINT, MVT::v4i32, MVT::v4f32, 1 },
459     { ISD::FP_TO_UINT, MVT::v2i64, MVT::v2f64, 1 },
460 
461     // Complex, from v2f32: legal type is v2i32 (no cost) or v2i64 (1 ext).
462     { ISD::FP_TO_SINT, MVT::v2i64, MVT::v2f32, 2 },
463     { ISD::FP_TO_SINT, MVT::v2i16, MVT::v2f32, 1 },
464     { ISD::FP_TO_SINT, MVT::v2i8,  MVT::v2f32, 1 },
465     { ISD::FP_TO_UINT, MVT::v2i64, MVT::v2f32, 2 },
466     { ISD::FP_TO_UINT, MVT::v2i16, MVT::v2f32, 1 },
467     { ISD::FP_TO_UINT, MVT::v2i8,  MVT::v2f32, 1 },
468 
469     // Complex, from v4f32: legal type is v4i16, 1 narrowing => ~2
470     { ISD::FP_TO_SINT, MVT::v4i16, MVT::v4f32, 2 },
471     { ISD::FP_TO_SINT, MVT::v4i8,  MVT::v4f32, 2 },
472     { ISD::FP_TO_UINT, MVT::v4i16, MVT::v4f32, 2 },
473     { ISD::FP_TO_UINT, MVT::v4i8,  MVT::v4f32, 2 },
474 
475     // Complex, from v2f64: legal type is v2i32, 1 narrowing => ~2.
476     { ISD::FP_TO_SINT, MVT::v2i32, MVT::v2f64, 2 },
477     { ISD::FP_TO_SINT, MVT::v2i16, MVT::v2f64, 2 },
478     { ISD::FP_TO_SINT, MVT::v2i8,  MVT::v2f64, 2 },
479     { ISD::FP_TO_UINT, MVT::v2i32, MVT::v2f64, 2 },
480     { ISD::FP_TO_UINT, MVT::v2i16, MVT::v2f64, 2 },
481     { ISD::FP_TO_UINT, MVT::v2i8,  MVT::v2f64, 2 },
482   };
483 
484   if (const auto *Entry = ConvertCostTableLookup(ConversionTbl, ISD,
485                                                  DstTy.getSimpleVT(),
486                                                  SrcTy.getSimpleVT()))
487     return AdjustCost(Entry->Cost);
488 
489   return AdjustCost(
490       BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I));
491 }
492 
493 int AArch64TTIImpl::getExtractWithExtendCost(unsigned Opcode, Type *Dst,
494                                              VectorType *VecTy,
495                                              unsigned Index) {
496 
497   // Make sure we were given a valid extend opcode.
498   assert((Opcode == Instruction::SExt || Opcode == Instruction::ZExt) &&
499          "Invalid opcode");
500 
501   // We are extending an element we extract from a vector, so the source type
502   // of the extend is the element type of the vector.
503   auto *Src = VecTy->getElementType();
504 
505   // Sign- and zero-extends are for integer types only.
506   assert(isa<IntegerType>(Dst) && isa<IntegerType>(Src) && "Invalid type");
507 
508   // Get the cost for the extract. We compute the cost (if any) for the extend
509   // below.
510   auto Cost = getVectorInstrCost(Instruction::ExtractElement, VecTy, Index);
511 
512   // Legalize the types.
513   auto VecLT = TLI->getTypeLegalizationCost(DL, VecTy);
514   auto DstVT = TLI->getValueType(DL, Dst);
515   auto SrcVT = TLI->getValueType(DL, Src);
516   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
517 
518   // If the resulting type is still a vector and the destination type is legal,
519   // we may get the extension for free. If not, get the default cost for the
520   // extend.
521   if (!VecLT.second.isVector() || !TLI->isTypeLegal(DstVT))
522     return Cost + getCastInstrCost(Opcode, Dst, Src, TTI::CastContextHint::None,
523                                    CostKind);
524 
525   // The destination type should be larger than the element type. If not, get
526   // the default cost for the extend.
527   if (DstVT.getFixedSizeInBits() < SrcVT.getFixedSizeInBits())
528     return Cost + getCastInstrCost(Opcode, Dst, Src, TTI::CastContextHint::None,
529                                    CostKind);
530 
531   switch (Opcode) {
532   default:
533     llvm_unreachable("Opcode should be either SExt or ZExt");
534 
535   // For sign-extends, we only need a smov, which performs the extension
536   // automatically.
537   case Instruction::SExt:
538     return Cost;
539 
540   // For zero-extends, the extend is performed automatically by a umov unless
541   // the destination type is i64 and the element type is i8 or i16.
542   case Instruction::ZExt:
543     if (DstVT.getSizeInBits() != 64u || SrcVT.getSizeInBits() == 32u)
544       return Cost;
545   }
546 
547   // If we are unable to perform the extend for free, get the default cost.
548   return Cost + getCastInstrCost(Opcode, Dst, Src, TTI::CastContextHint::None,
549                                  CostKind);
550 }
551 
552 unsigned AArch64TTIImpl::getCFInstrCost(unsigned Opcode,
553                                         TTI::TargetCostKind CostKind) {
554   if (CostKind != TTI::TCK_RecipThroughput)
555     return Opcode == Instruction::PHI ? 0 : 1;
556   assert(CostKind == TTI::TCK_RecipThroughput && "unexpected CostKind");
557   // Branches are assumed to be predicted.
558   return 0;
559 }
560 
561 int AArch64TTIImpl::getVectorInstrCost(unsigned Opcode, Type *Val,
562                                        unsigned Index) {
563   assert(Val->isVectorTy() && "This must be a vector type");
564 
565   if (Index != -1U) {
566     // Legalize the type.
567     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Val);
568 
569     // This type is legalized to a scalar type.
570     if (!LT.second.isVector())
571       return 0;
572 
573     // The type may be split. Normalize the index to the new type.
574     unsigned Width = LT.second.getVectorNumElements();
575     Index = Index % Width;
576 
577     // The element at index zero is already inside the vector.
578     if (Index == 0)
579       return 0;
580   }
581 
582   // All other insert/extracts cost this much.
583   return ST->getVectorInsertExtractBaseCost();
584 }
585 
586 int AArch64TTIImpl::getArithmeticInstrCost(
587     unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind,
588     TTI::OperandValueKind Opd1Info,
589     TTI::OperandValueKind Opd2Info, TTI::OperandValueProperties Opd1PropInfo,
590     TTI::OperandValueProperties Opd2PropInfo, ArrayRef<const Value *> Args,
591     const Instruction *CxtI) {
592   // TODO: Handle more cost kinds.
593   if (CostKind != TTI::TCK_RecipThroughput)
594     return BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info,
595                                          Opd2Info, Opd1PropInfo,
596                                          Opd2PropInfo, Args, CxtI);
597 
598   // Legalize the type.
599   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
600 
601   // If the instruction is a widening instruction (e.g., uaddl, saddw, etc.),
602   // add in the widening overhead specified by the sub-target. Since the
603   // extends feeding widening instructions are performed automatically, they
604   // aren't present in the generated code and have a zero cost. By adding a
605   // widening overhead here, we attach the total cost of the combined operation
606   // to the widening instruction.
607   int Cost = 0;
608   if (isWideningInstruction(Ty, Opcode, Args))
609     Cost += ST->getWideningBaseCost();
610 
611   int ISD = TLI->InstructionOpcodeToISD(Opcode);
612 
613   switch (ISD) {
614   default:
615     return Cost + BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info,
616                                                 Opd2Info,
617                                                 Opd1PropInfo, Opd2PropInfo);
618   case ISD::SDIV:
619     if (Opd2Info == TargetTransformInfo::OK_UniformConstantValue &&
620         Opd2PropInfo == TargetTransformInfo::OP_PowerOf2) {
621       // On AArch64, scalar signed division by constants power-of-two are
622       // normally expanded to the sequence ADD + CMP + SELECT + SRA.
623       // The OperandValue properties many not be same as that of previous
624       // operation; conservatively assume OP_None.
625       Cost += getArithmeticInstrCost(Instruction::Add, Ty, CostKind,
626                                      Opd1Info, Opd2Info,
627                                      TargetTransformInfo::OP_None,
628                                      TargetTransformInfo::OP_None);
629       Cost += getArithmeticInstrCost(Instruction::Sub, Ty, CostKind,
630                                      Opd1Info, Opd2Info,
631                                      TargetTransformInfo::OP_None,
632                                      TargetTransformInfo::OP_None);
633       Cost += getArithmeticInstrCost(Instruction::Select, Ty, CostKind,
634                                      Opd1Info, Opd2Info,
635                                      TargetTransformInfo::OP_None,
636                                      TargetTransformInfo::OP_None);
637       Cost += getArithmeticInstrCost(Instruction::AShr, Ty, CostKind,
638                                      Opd1Info, Opd2Info,
639                                      TargetTransformInfo::OP_None,
640                                      TargetTransformInfo::OP_None);
641       return Cost;
642     }
643     LLVM_FALLTHROUGH;
644   case ISD::UDIV:
645     if (Opd2Info == TargetTransformInfo::OK_UniformConstantValue) {
646       auto VT = TLI->getValueType(DL, Ty);
647       if (TLI->isOperationLegalOrCustom(ISD::MULHU, VT)) {
648         // Vector signed division by constant are expanded to the
649         // sequence MULHS + ADD/SUB + SRA + SRL + ADD, and unsigned division
650         // to MULHS + SUB + SRL + ADD + SRL.
651         int MulCost = getArithmeticInstrCost(Instruction::Mul, Ty, CostKind,
652                                              Opd1Info, Opd2Info,
653                                              TargetTransformInfo::OP_None,
654                                              TargetTransformInfo::OP_None);
655         int AddCost = getArithmeticInstrCost(Instruction::Add, Ty, CostKind,
656                                              Opd1Info, Opd2Info,
657                                              TargetTransformInfo::OP_None,
658                                              TargetTransformInfo::OP_None);
659         int ShrCost = getArithmeticInstrCost(Instruction::AShr, Ty, CostKind,
660                                              Opd1Info, Opd2Info,
661                                              TargetTransformInfo::OP_None,
662                                              TargetTransformInfo::OP_None);
663         return MulCost * 2 + AddCost * 2 + ShrCost * 2 + 1;
664       }
665     }
666 
667     Cost += BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info,
668                                           Opd2Info,
669                                           Opd1PropInfo, Opd2PropInfo);
670     if (Ty->isVectorTy()) {
671       // On AArch64, vector divisions are not supported natively and are
672       // expanded into scalar divisions of each pair of elements.
673       Cost += getArithmeticInstrCost(Instruction::ExtractElement, Ty, CostKind,
674                                      Opd1Info, Opd2Info, Opd1PropInfo,
675                                      Opd2PropInfo);
676       Cost += getArithmeticInstrCost(Instruction::InsertElement, Ty, CostKind,
677                                      Opd1Info, Opd2Info, Opd1PropInfo,
678                                      Opd2PropInfo);
679       // TODO: if one of the arguments is scalar, then it's not necessary to
680       // double the cost of handling the vector elements.
681       Cost += Cost;
682     }
683     return Cost;
684 
685   case ISD::MUL:
686     if (LT.second != MVT::v2i64)
687       return (Cost + 1) * LT.first;
688     // Since we do not have a MUL.2d instruction, a mul <2 x i64> is expensive
689     // as elements are extracted from the vectors and the muls scalarized.
690     // As getScalarizationOverhead is a bit too pessimistic, we estimate the
691     // cost for a i64 vector directly here, which is:
692     // - four i64 extracts,
693     // - two i64 inserts, and
694     // - two muls.
695     // So, for a v2i64 with LT.First = 1 the cost is 8, and for a v4i64 with
696     // LT.first = 2 the cost is 16.
697     return LT.first * 8;
698   case ISD::ADD:
699   case ISD::XOR:
700   case ISD::OR:
701   case ISD::AND:
702     // These nodes are marked as 'custom' for combining purposes only.
703     // We know that they are legal. See LowerAdd in ISelLowering.
704     return (Cost + 1) * LT.first;
705 
706   case ISD::FADD:
707     // These nodes are marked as 'custom' just to lower them to SVE.
708     // We know said lowering will incur no additional cost.
709     if (isa<FixedVectorType>(Ty) && !Ty->getScalarType()->isFP128Ty())
710       return (Cost + 2) * LT.first;
711 
712     return Cost + BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Opd1Info,
713                                                 Opd2Info,
714                                                 Opd1PropInfo, Opd2PropInfo);
715   }
716 }
717 
718 int AArch64TTIImpl::getAddressComputationCost(Type *Ty, ScalarEvolution *SE,
719                                               const SCEV *Ptr) {
720   // Address computations in vectorized code with non-consecutive addresses will
721   // likely result in more instructions compared to scalar code where the
722   // computation can more often be merged into the index mode. The resulting
723   // extra micro-ops can significantly decrease throughput.
724   unsigned NumVectorInstToHideOverhead = 10;
725   int MaxMergeDistance = 64;
726 
727   if (Ty->isVectorTy() && SE &&
728       !BaseT::isConstantStridedAccessLessThan(SE, Ptr, MaxMergeDistance + 1))
729     return NumVectorInstToHideOverhead;
730 
731   // In many cases the address computation is not merged into the instruction
732   // addressing mode.
733   return 1;
734 }
735 
736 int AArch64TTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy,
737                                        Type *CondTy, CmpInst::Predicate VecPred,
738                                        TTI::TargetCostKind CostKind,
739                                        const Instruction *I) {
740   // TODO: Handle other cost kinds.
741   if (CostKind != TTI::TCK_RecipThroughput)
742     return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind,
743                                      I);
744 
745   int ISD = TLI->InstructionOpcodeToISD(Opcode);
746   // We don't lower some vector selects well that are wider than the register
747   // width.
748   if (isa<FixedVectorType>(ValTy) && ISD == ISD::SELECT) {
749     // We would need this many instructions to hide the scalarization happening.
750     const int AmortizationCost = 20;
751 
752     // If VecPred is not set, check if we can get a predicate from the context
753     // instruction, if its type matches the requested ValTy.
754     if (VecPred == CmpInst::BAD_ICMP_PREDICATE && I && I->getType() == ValTy) {
755       CmpInst::Predicate CurrentPred;
756       if (match(I, m_Select(m_Cmp(CurrentPred, m_Value(), m_Value()), m_Value(),
757                             m_Value())))
758         VecPred = CurrentPred;
759     }
760     // Check if we have a compare/select chain that can be lowered using CMxx &
761     // BFI pair.
762     if (CmpInst::isIntPredicate(VecPred)) {
763       static const auto ValidMinMaxTys = {MVT::v8i8,  MVT::v16i8, MVT::v4i16,
764                                           MVT::v8i16, MVT::v2i32, MVT::v4i32,
765                                           MVT::v2i64};
766       auto LT = TLI->getTypeLegalizationCost(DL, ValTy);
767       if (any_of(ValidMinMaxTys, [&LT](MVT M) { return M == LT.second; }))
768         return LT.first;
769     }
770 
771     static const TypeConversionCostTblEntry
772     VectorSelectTbl[] = {
773       { ISD::SELECT, MVT::v16i1, MVT::v16i16, 16 },
774       { ISD::SELECT, MVT::v8i1, MVT::v8i32, 8 },
775       { ISD::SELECT, MVT::v16i1, MVT::v16i32, 16 },
776       { ISD::SELECT, MVT::v4i1, MVT::v4i64, 4 * AmortizationCost },
777       { ISD::SELECT, MVT::v8i1, MVT::v8i64, 8 * AmortizationCost },
778       { ISD::SELECT, MVT::v16i1, MVT::v16i64, 16 * AmortizationCost }
779     };
780 
781     EVT SelCondTy = TLI->getValueType(DL, CondTy);
782     EVT SelValTy = TLI->getValueType(DL, ValTy);
783     if (SelCondTy.isSimple() && SelValTy.isSimple()) {
784       if (const auto *Entry = ConvertCostTableLookup(VectorSelectTbl, ISD,
785                                                      SelCondTy.getSimpleVT(),
786                                                      SelValTy.getSimpleVT()))
787         return Entry->Cost;
788     }
789   }
790   // The base case handles scalable vectors fine for now, since it treats the
791   // cost as 1 * legalization cost.
792   return BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind, I);
793 }
794 
795 AArch64TTIImpl::TTI::MemCmpExpansionOptions
796 AArch64TTIImpl::enableMemCmpExpansion(bool OptSize, bool IsZeroCmp) const {
797   TTI::MemCmpExpansionOptions Options;
798   if (ST->requiresStrictAlign()) {
799     // TODO: Add cost modeling for strict align. Misaligned loads expand to
800     // a bunch of instructions when strict align is enabled.
801     return Options;
802   }
803   Options.AllowOverlappingLoads = true;
804   Options.MaxNumLoads = TLI->getMaxExpandSizeMemcmp(OptSize);
805   Options.NumLoadsPerBlock = Options.MaxNumLoads;
806   // TODO: Though vector loads usually perform well on AArch64, in some targets
807   // they may wake up the FP unit, which raises the power consumption.  Perhaps
808   // they could be used with no holds barred (-O3).
809   Options.LoadSizes = {8, 4, 2, 1};
810   return Options;
811 }
812 
813 unsigned AArch64TTIImpl::getGatherScatterOpCost(
814     unsigned Opcode, Type *DataTy, const Value *Ptr, bool VariableMask,
815     Align Alignment, TTI::TargetCostKind CostKind, const Instruction *I) {
816 
817   if (!isa<ScalableVectorType>(DataTy))
818     return BaseT::getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
819                                          Alignment, CostKind, I);
820   auto *VT = cast<VectorType>(DataTy);
821   auto LT = TLI->getTypeLegalizationCost(DL, DataTy);
822   ElementCount LegalVF = LT.second.getVectorElementCount();
823   Optional<unsigned> MaxNumVScale = getMaxVScale();
824   assert(MaxNumVScale && "Expected valid max vscale value");
825 
826   unsigned MemOpCost =
827       getMemoryOpCost(Opcode, VT->getElementType(), Alignment, 0, CostKind, I);
828   unsigned MaxNumElementsPerGather =
829       MaxNumVScale.getValue() * LegalVF.getKnownMinValue();
830   return LT.first * MaxNumElementsPerGather * MemOpCost;
831 }
832 
833 bool AArch64TTIImpl::useNeonVector(const Type *Ty) const {
834   return isa<FixedVectorType>(Ty) && !ST->useSVEForFixedLengthVectors();
835 }
836 
837 int AArch64TTIImpl::getMemoryOpCost(unsigned Opcode, Type *Ty,
838                                     MaybeAlign Alignment, unsigned AddressSpace,
839                                     TTI::TargetCostKind CostKind,
840                                     const Instruction *I) {
841   // TODO: Handle other cost kinds.
842   if (CostKind != TTI::TCK_RecipThroughput)
843     return 1;
844 
845   // Type legalization can't handle structs
846   if (TLI->getValueType(DL, Ty,  true) == MVT::Other)
847     return BaseT::getMemoryOpCost(Opcode, Ty, Alignment, AddressSpace,
848                                   CostKind);
849 
850   auto LT = TLI->getTypeLegalizationCost(DL, Ty);
851 
852   if (ST->isMisaligned128StoreSlow() && Opcode == Instruction::Store &&
853       LT.second.is128BitVector() && (!Alignment || *Alignment < Align(16))) {
854     // Unaligned stores are extremely inefficient. We don't split all
855     // unaligned 128-bit stores because the negative impact that has shown in
856     // practice on inlined block copy code.
857     // We make such stores expensive so that we will only vectorize if there
858     // are 6 other instructions getting vectorized.
859     const int AmortizationCost = 6;
860 
861     return LT.first * 2 * AmortizationCost;
862   }
863 
864   if (useNeonVector(Ty) &&
865       cast<VectorType>(Ty)->getElementType()->isIntegerTy(8)) {
866     unsigned ProfitableNumElements;
867     if (Opcode == Instruction::Store)
868       // We use a custom trunc store lowering so v.4b should be profitable.
869       ProfitableNumElements = 4;
870     else
871       // We scalarize the loads because there is not v.4b register and we
872       // have to promote the elements to v.2.
873       ProfitableNumElements = 8;
874 
875     if (cast<FixedVectorType>(Ty)->getNumElements() < ProfitableNumElements) {
876       unsigned NumVecElts = cast<FixedVectorType>(Ty)->getNumElements();
877       unsigned NumVectorizableInstsToAmortize = NumVecElts * 2;
878       // We generate 2 instructions per vector element.
879       return NumVectorizableInstsToAmortize * NumVecElts * 2;
880     }
881   }
882 
883   return LT.first;
884 }
885 
886 int AArch64TTIImpl::getInterleavedMemoryOpCost(
887     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
888     Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
889     bool UseMaskForCond, bool UseMaskForGaps) {
890   assert(Factor >= 2 && "Invalid interleave factor");
891   auto *VecVTy = cast<FixedVectorType>(VecTy);
892 
893   if (!UseMaskForCond && !UseMaskForGaps &&
894       Factor <= TLI->getMaxSupportedInterleaveFactor()) {
895     unsigned NumElts = VecVTy->getNumElements();
896     auto *SubVecTy =
897         FixedVectorType::get(VecTy->getScalarType(), NumElts / Factor);
898 
899     // ldN/stN only support legal vector types of size 64 or 128 in bits.
900     // Accesses having vector types that are a multiple of 128 bits can be
901     // matched to more than one ldN/stN instruction.
902     if (NumElts % Factor == 0 &&
903         TLI->isLegalInterleavedAccessType(SubVecTy, DL))
904       return Factor * TLI->getNumInterleavedAccesses(SubVecTy, DL);
905   }
906 
907   return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
908                                            Alignment, AddressSpace, CostKind,
909                                            UseMaskForCond, UseMaskForGaps);
910 }
911 
912 int AArch64TTIImpl::getCostOfKeepingLiveOverCall(ArrayRef<Type *> Tys) {
913   int Cost = 0;
914   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
915   for (auto *I : Tys) {
916     if (!I->isVectorTy())
917       continue;
918     if (I->getScalarSizeInBits() * cast<FixedVectorType>(I)->getNumElements() ==
919         128)
920       Cost += getMemoryOpCost(Instruction::Store, I, Align(128), 0, CostKind) +
921               getMemoryOpCost(Instruction::Load, I, Align(128), 0, CostKind);
922   }
923   return Cost;
924 }
925 
926 unsigned AArch64TTIImpl::getMaxInterleaveFactor(unsigned VF) {
927   return ST->getMaxInterleaveFactor();
928 }
929 
930 // For Falkor, we want to avoid having too many strided loads in a loop since
931 // that can exhaust the HW prefetcher resources.  We adjust the unroller
932 // MaxCount preference below to attempt to ensure unrolling doesn't create too
933 // many strided loads.
934 static void
935 getFalkorUnrollingPreferences(Loop *L, ScalarEvolution &SE,
936                               TargetTransformInfo::UnrollingPreferences &UP) {
937   enum { MaxStridedLoads = 7 };
938   auto countStridedLoads = [](Loop *L, ScalarEvolution &SE) {
939     int StridedLoads = 0;
940     // FIXME? We could make this more precise by looking at the CFG and
941     // e.g. not counting loads in each side of an if-then-else diamond.
942     for (const auto BB : L->blocks()) {
943       for (auto &I : *BB) {
944         LoadInst *LMemI = dyn_cast<LoadInst>(&I);
945         if (!LMemI)
946           continue;
947 
948         Value *PtrValue = LMemI->getPointerOperand();
949         if (L->isLoopInvariant(PtrValue))
950           continue;
951 
952         const SCEV *LSCEV = SE.getSCEV(PtrValue);
953         const SCEVAddRecExpr *LSCEVAddRec = dyn_cast<SCEVAddRecExpr>(LSCEV);
954         if (!LSCEVAddRec || !LSCEVAddRec->isAffine())
955           continue;
956 
957         // FIXME? We could take pairing of unrolled load copies into account
958         // by looking at the AddRec, but we would probably have to limit this
959         // to loops with no stores or other memory optimization barriers.
960         ++StridedLoads;
961         // We've seen enough strided loads that seeing more won't make a
962         // difference.
963         if (StridedLoads > MaxStridedLoads / 2)
964           return StridedLoads;
965       }
966     }
967     return StridedLoads;
968   };
969 
970   int StridedLoads = countStridedLoads(L, SE);
971   LLVM_DEBUG(dbgs() << "falkor-hwpf: detected " << StridedLoads
972                     << " strided loads\n");
973   // Pick the largest power of 2 unroll count that won't result in too many
974   // strided loads.
975   if (StridedLoads) {
976     UP.MaxCount = 1 << Log2_32(MaxStridedLoads / StridedLoads);
977     LLVM_DEBUG(dbgs() << "falkor-hwpf: setting unroll MaxCount to "
978                       << UP.MaxCount << '\n');
979   }
980 }
981 
982 void AArch64TTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
983                                              TTI::UnrollingPreferences &UP) {
984   // Enable partial unrolling and runtime unrolling.
985   BaseT::getUnrollingPreferences(L, SE, UP);
986 
987   // For inner loop, it is more likely to be a hot one, and the runtime check
988   // can be promoted out from LICM pass, so the overhead is less, let's try
989   // a larger threshold to unroll more loops.
990   if (L->getLoopDepth() > 1)
991     UP.PartialThreshold *= 2;
992 
993   // Disable partial & runtime unrolling on -Os.
994   UP.PartialOptSizeThreshold = 0;
995 
996   if (ST->getProcFamily() == AArch64Subtarget::Falkor &&
997       EnableFalkorHWPFUnrollFix)
998     getFalkorUnrollingPreferences(L, SE, UP);
999 }
1000 
1001 void AArch64TTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
1002                                            TTI::PeelingPreferences &PP) {
1003   BaseT::getPeelingPreferences(L, SE, PP);
1004 }
1005 
1006 Value *AArch64TTIImpl::getOrCreateResultFromMemIntrinsic(IntrinsicInst *Inst,
1007                                                          Type *ExpectedType) {
1008   switch (Inst->getIntrinsicID()) {
1009   default:
1010     return nullptr;
1011   case Intrinsic::aarch64_neon_st2:
1012   case Intrinsic::aarch64_neon_st3:
1013   case Intrinsic::aarch64_neon_st4: {
1014     // Create a struct type
1015     StructType *ST = dyn_cast<StructType>(ExpectedType);
1016     if (!ST)
1017       return nullptr;
1018     unsigned NumElts = Inst->getNumArgOperands() - 1;
1019     if (ST->getNumElements() != NumElts)
1020       return nullptr;
1021     for (unsigned i = 0, e = NumElts; i != e; ++i) {
1022       if (Inst->getArgOperand(i)->getType() != ST->getElementType(i))
1023         return nullptr;
1024     }
1025     Value *Res = UndefValue::get(ExpectedType);
1026     IRBuilder<> Builder(Inst);
1027     for (unsigned i = 0, e = NumElts; i != e; ++i) {
1028       Value *L = Inst->getArgOperand(i);
1029       Res = Builder.CreateInsertValue(Res, L, i);
1030     }
1031     return Res;
1032   }
1033   case Intrinsic::aarch64_neon_ld2:
1034   case Intrinsic::aarch64_neon_ld3:
1035   case Intrinsic::aarch64_neon_ld4:
1036     if (Inst->getType() == ExpectedType)
1037       return Inst;
1038     return nullptr;
1039   }
1040 }
1041 
1042 bool AArch64TTIImpl::getTgtMemIntrinsic(IntrinsicInst *Inst,
1043                                         MemIntrinsicInfo &Info) {
1044   switch (Inst->getIntrinsicID()) {
1045   default:
1046     break;
1047   case Intrinsic::aarch64_neon_ld2:
1048   case Intrinsic::aarch64_neon_ld3:
1049   case Intrinsic::aarch64_neon_ld4:
1050     Info.ReadMem = true;
1051     Info.WriteMem = false;
1052     Info.PtrVal = Inst->getArgOperand(0);
1053     break;
1054   case Intrinsic::aarch64_neon_st2:
1055   case Intrinsic::aarch64_neon_st3:
1056   case Intrinsic::aarch64_neon_st4:
1057     Info.ReadMem = false;
1058     Info.WriteMem = true;
1059     Info.PtrVal = Inst->getArgOperand(Inst->getNumArgOperands() - 1);
1060     break;
1061   }
1062 
1063   switch (Inst->getIntrinsicID()) {
1064   default:
1065     return false;
1066   case Intrinsic::aarch64_neon_ld2:
1067   case Intrinsic::aarch64_neon_st2:
1068     Info.MatchingId = VECTOR_LDST_TWO_ELEMENTS;
1069     break;
1070   case Intrinsic::aarch64_neon_ld3:
1071   case Intrinsic::aarch64_neon_st3:
1072     Info.MatchingId = VECTOR_LDST_THREE_ELEMENTS;
1073     break;
1074   case Intrinsic::aarch64_neon_ld4:
1075   case Intrinsic::aarch64_neon_st4:
1076     Info.MatchingId = VECTOR_LDST_FOUR_ELEMENTS;
1077     break;
1078   }
1079   return true;
1080 }
1081 
1082 /// See if \p I should be considered for address type promotion. We check if \p
1083 /// I is a sext with right type and used in memory accesses. If it used in a
1084 /// "complex" getelementptr, we allow it to be promoted without finding other
1085 /// sext instructions that sign extended the same initial value. A getelementptr
1086 /// is considered as "complex" if it has more than 2 operands.
1087 bool AArch64TTIImpl::shouldConsiderAddressTypePromotion(
1088     const Instruction &I, bool &AllowPromotionWithoutCommonHeader) {
1089   bool Considerable = false;
1090   AllowPromotionWithoutCommonHeader = false;
1091   if (!isa<SExtInst>(&I))
1092     return false;
1093   Type *ConsideredSExtType =
1094       Type::getInt64Ty(I.getParent()->getParent()->getContext());
1095   if (I.getType() != ConsideredSExtType)
1096     return false;
1097   // See if the sext is the one with the right type and used in at least one
1098   // GetElementPtrInst.
1099   for (const User *U : I.users()) {
1100     if (const GetElementPtrInst *GEPInst = dyn_cast<GetElementPtrInst>(U)) {
1101       Considerable = true;
1102       // A getelementptr is considered as "complex" if it has more than 2
1103       // operands. We will promote a SExt used in such complex GEP as we
1104       // expect some computation to be merged if they are done on 64 bits.
1105       if (GEPInst->getNumOperands() > 2) {
1106         AllowPromotionWithoutCommonHeader = true;
1107         break;
1108       }
1109     }
1110   }
1111   return Considerable;
1112 }
1113 
1114 bool AArch64TTIImpl::isLegalToVectorizeReduction(RecurrenceDescriptor RdxDesc,
1115                                                  ElementCount VF) const {
1116   if (!VF.isScalable())
1117     return true;
1118 
1119   Type *Ty = RdxDesc.getRecurrenceType();
1120   if (Ty->isBFloatTy() || !isLegalElementTypeForSVE(Ty))
1121     return false;
1122 
1123   switch (RdxDesc.getRecurrenceKind()) {
1124   case RecurKind::Add:
1125   case RecurKind::FAdd:
1126   case RecurKind::And:
1127   case RecurKind::Or:
1128   case RecurKind::Xor:
1129   case RecurKind::SMin:
1130   case RecurKind::SMax:
1131   case RecurKind::UMin:
1132   case RecurKind::UMax:
1133   case RecurKind::FMin:
1134   case RecurKind::FMax:
1135     return true;
1136   default:
1137     return false;
1138   }
1139 }
1140 
1141 int AArch64TTIImpl::getMinMaxReductionCost(VectorType *Ty, VectorType *CondTy,
1142                                            bool IsPairwise, bool IsUnsigned,
1143                                            TTI::TargetCostKind CostKind) {
1144   if (!isa<ScalableVectorType>(Ty))
1145     return BaseT::getMinMaxReductionCost(Ty, CondTy, IsPairwise, IsUnsigned,
1146                                          CostKind);
1147   assert((isa<ScalableVectorType>(Ty) && isa<ScalableVectorType>(CondTy)) &&
1148          "Both vector needs to be scalable");
1149 
1150   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
1151   int LegalizationCost = 0;
1152   if (LT.first > 1) {
1153     Type *LegalVTy = EVT(LT.second).getTypeForEVT(Ty->getContext());
1154     unsigned CmpOpcode =
1155         Ty->isFPOrFPVectorTy() ? Instruction::FCmp : Instruction::ICmp;
1156     LegalizationCost =
1157         getCmpSelInstrCost(CmpOpcode, LegalVTy, LegalVTy,
1158                            CmpInst::BAD_ICMP_PREDICATE, CostKind) +
1159         getCmpSelInstrCost(Instruction::Select, LegalVTy, LegalVTy,
1160                            CmpInst::BAD_ICMP_PREDICATE, CostKind);
1161     LegalizationCost *= LT.first - 1;
1162   }
1163 
1164   return LegalizationCost + /*Cost of horizontal reduction*/ 2;
1165 }
1166 
1167 int AArch64TTIImpl::getArithmeticReductionCostSVE(
1168     unsigned Opcode, VectorType *ValTy, bool IsPairwise,
1169     TTI::TargetCostKind CostKind) {
1170   assert(!IsPairwise && "Cannot be pair wise to continue");
1171 
1172   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
1173   int LegalizationCost = 0;
1174   if (LT.first > 1) {
1175     Type *LegalVTy = EVT(LT.second).getTypeForEVT(ValTy->getContext());
1176     LegalizationCost = getArithmeticInstrCost(Opcode, LegalVTy, CostKind);
1177     LegalizationCost *= LT.first - 1;
1178   }
1179 
1180   int ISD = TLI->InstructionOpcodeToISD(Opcode);
1181   assert(ISD && "Invalid opcode");
1182   // Add the final reduction cost for the legal horizontal reduction
1183   switch (ISD) {
1184   case ISD::ADD:
1185   case ISD::AND:
1186   case ISD::OR:
1187   case ISD::XOR:
1188   case ISD::FADD:
1189     return LegalizationCost + 2;
1190   default:
1191     // TODO: Replace for invalid when InstructionCost is used
1192     // cases not supported by SVE
1193     return 16;
1194   }
1195 }
1196 
1197 int AArch64TTIImpl::getArithmeticReductionCost(unsigned Opcode,
1198                                                VectorType *ValTy,
1199                                                bool IsPairwiseForm,
1200                                                TTI::TargetCostKind CostKind) {
1201 
1202   if (isa<ScalableVectorType>(ValTy))
1203     return getArithmeticReductionCostSVE(Opcode, ValTy, IsPairwiseForm,
1204                                          CostKind);
1205   if (IsPairwiseForm)
1206     return BaseT::getArithmeticReductionCost(Opcode, ValTy, IsPairwiseForm,
1207                                              CostKind);
1208 
1209   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
1210   MVT MTy = LT.second;
1211   int ISD = TLI->InstructionOpcodeToISD(Opcode);
1212   assert(ISD && "Invalid opcode");
1213 
1214   // Horizontal adds can use the 'addv' instruction. We model the cost of these
1215   // instructions as normal vector adds. This is the only arithmetic vector
1216   // reduction operation for which we have an instruction.
1217   static const CostTblEntry CostTblNoPairwise[]{
1218       {ISD::ADD, MVT::v8i8,  1},
1219       {ISD::ADD, MVT::v16i8, 1},
1220       {ISD::ADD, MVT::v4i16, 1},
1221       {ISD::ADD, MVT::v8i16, 1},
1222       {ISD::ADD, MVT::v4i32, 1},
1223   };
1224 
1225   if (const auto *Entry = CostTableLookup(CostTblNoPairwise, ISD, MTy))
1226     return LT.first * Entry->Cost;
1227 
1228   return BaseT::getArithmeticReductionCost(Opcode, ValTy, IsPairwiseForm,
1229                                            CostKind);
1230 }
1231 
1232 int AArch64TTIImpl::getShuffleCost(TTI::ShuffleKind Kind, VectorType *Tp,
1233                                    ArrayRef<int> Mask, int Index,
1234                                    VectorType *SubTp) {
1235   if (Kind == TTI::SK_Broadcast || Kind == TTI::SK_Transpose ||
1236       Kind == TTI::SK_Select || Kind == TTI::SK_PermuteSingleSrc ||
1237       Kind == TTI::SK_Reverse) {
1238     static const CostTblEntry ShuffleTbl[] = {
1239       // Broadcast shuffle kinds can be performed with 'dup'.
1240       { TTI::SK_Broadcast, MVT::v8i8,  1 },
1241       { TTI::SK_Broadcast, MVT::v16i8, 1 },
1242       { TTI::SK_Broadcast, MVT::v4i16, 1 },
1243       { TTI::SK_Broadcast, MVT::v8i16, 1 },
1244       { TTI::SK_Broadcast, MVT::v2i32, 1 },
1245       { TTI::SK_Broadcast, MVT::v4i32, 1 },
1246       { TTI::SK_Broadcast, MVT::v2i64, 1 },
1247       { TTI::SK_Broadcast, MVT::v2f32, 1 },
1248       { TTI::SK_Broadcast, MVT::v4f32, 1 },
1249       { TTI::SK_Broadcast, MVT::v2f64, 1 },
1250       // Transpose shuffle kinds can be performed with 'trn1/trn2' and
1251       // 'zip1/zip2' instructions.
1252       { TTI::SK_Transpose, MVT::v8i8,  1 },
1253       { TTI::SK_Transpose, MVT::v16i8, 1 },
1254       { TTI::SK_Transpose, MVT::v4i16, 1 },
1255       { TTI::SK_Transpose, MVT::v8i16, 1 },
1256       { TTI::SK_Transpose, MVT::v2i32, 1 },
1257       { TTI::SK_Transpose, MVT::v4i32, 1 },
1258       { TTI::SK_Transpose, MVT::v2i64, 1 },
1259       { TTI::SK_Transpose, MVT::v2f32, 1 },
1260       { TTI::SK_Transpose, MVT::v4f32, 1 },
1261       { TTI::SK_Transpose, MVT::v2f64, 1 },
1262       // Select shuffle kinds.
1263       // TODO: handle vXi8/vXi16.
1264       { TTI::SK_Select, MVT::v2i32, 1 }, // mov.
1265       { TTI::SK_Select, MVT::v4i32, 2 }, // rev+trn (or similar).
1266       { TTI::SK_Select, MVT::v2i64, 1 }, // mov.
1267       { TTI::SK_Select, MVT::v2f32, 1 }, // mov.
1268       { TTI::SK_Select, MVT::v4f32, 2 }, // rev+trn (or similar).
1269       { TTI::SK_Select, MVT::v2f64, 1 }, // mov.
1270       // PermuteSingleSrc shuffle kinds.
1271       // TODO: handle vXi8/vXi16.
1272       { TTI::SK_PermuteSingleSrc, MVT::v2i32, 1 }, // mov.
1273       { TTI::SK_PermuteSingleSrc, MVT::v4i32, 3 }, // perfectshuffle worst case.
1274       { TTI::SK_PermuteSingleSrc, MVT::v2i64, 1 }, // mov.
1275       { TTI::SK_PermuteSingleSrc, MVT::v2f32, 1 }, // mov.
1276       { TTI::SK_PermuteSingleSrc, MVT::v4f32, 3 }, // perfectshuffle worst case.
1277       { TTI::SK_PermuteSingleSrc, MVT::v2f64, 1 }, // mov.
1278       // Broadcast shuffle kinds for scalable vectors
1279       { TTI::SK_Broadcast, MVT::nxv16i8,  1 },
1280       { TTI::SK_Broadcast, MVT::nxv8i16,  1 },
1281       { TTI::SK_Broadcast, MVT::nxv4i32,  1 },
1282       { TTI::SK_Broadcast, MVT::nxv2i64,  1 },
1283       { TTI::SK_Broadcast, MVT::nxv8f16,  1 },
1284       { TTI::SK_Broadcast, MVT::nxv8bf16, 1 },
1285       { TTI::SK_Broadcast, MVT::nxv4f32,  1 },
1286       { TTI::SK_Broadcast, MVT::nxv2f64,  1 },
1287       // Handle the cases for vector.reverse with scalable vectors
1288       { TTI::SK_Reverse, MVT::nxv16i8,  1 },
1289       { TTI::SK_Reverse, MVT::nxv8i16,  1 },
1290       { TTI::SK_Reverse, MVT::nxv4i32,  1 },
1291       { TTI::SK_Reverse, MVT::nxv2i64,  1 },
1292       { TTI::SK_Reverse, MVT::nxv8f16,  1 },
1293       { TTI::SK_Reverse, MVT::nxv8bf16, 1 },
1294       { TTI::SK_Reverse, MVT::nxv4f32,  1 },
1295       { TTI::SK_Reverse, MVT::nxv2f64,  1 },
1296       { TTI::SK_Reverse, MVT::nxv16i1,  1 },
1297       { TTI::SK_Reverse, MVT::nxv8i1,   1 },
1298       { TTI::SK_Reverse, MVT::nxv4i1,   1 },
1299       { TTI::SK_Reverse, MVT::nxv2i1,   1 },
1300     };
1301     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
1302     if (const auto *Entry = CostTableLookup(ShuffleTbl, Kind, LT.second))
1303       return LT.first * Entry->Cost;
1304   }
1305 
1306   return BaseT::getShuffleCost(Kind, Tp, Mask, Index, SubTp);
1307 }
1308