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