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