1 //===- ARMTargetTransformInfo.cpp - ARM 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 "ARMTargetTransformInfo.h"
10 #include "ARMSubtarget.h"
11 #include "MCTargetDesc/ARMAddressingModes.h"
12 #include "llvm/ADT/APInt.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/Analysis/LoopInfo.h"
15 #include "llvm/CodeGen/CostTable.h"
16 #include "llvm/CodeGen/ISDOpcodes.h"
17 #include "llvm/CodeGen/ValueTypes.h"
18 #include "llvm/IR/BasicBlock.h"
19 #include "llvm/IR/DataLayout.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/Instruction.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Intrinsics.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/IntrinsicsARM.h"
26 #include "llvm/IR/PatternMatch.h"
27 #include "llvm/IR/Type.h"
28 #include "llvm/MC/SubtargetFeature.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/KnownBits.h"
31 #include "llvm/Support/MachineValueType.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Transforms/InstCombine/InstCombiner.h"
34 #include "llvm/Transforms/Utils/Local.h"
35 #include "llvm/Transforms/Utils/LoopUtils.h"
36 #include <algorithm>
37 #include <cassert>
38 #include <cstdint>
39 #include <utility>
40 
41 using namespace llvm;
42 
43 #define DEBUG_TYPE "armtti"
44 
45 static cl::opt<bool> EnableMaskedLoadStores(
46   "enable-arm-maskedldst", cl::Hidden, cl::init(true),
47   cl::desc("Enable the generation of masked loads and stores"));
48 
49 static cl::opt<bool> DisableLowOverheadLoops(
50   "disable-arm-loloops", cl::Hidden, cl::init(false),
51   cl::desc("Disable the generation of low-overhead loops"));
52 
53 static cl::opt<bool>
54     AllowWLSLoops("allow-arm-wlsloops", cl::Hidden, cl::init(true),
55                   cl::desc("Enable the generation of WLS loops"));
56 
57 extern cl::opt<TailPredication::Mode> EnableTailPredication;
58 
59 extern cl::opt<bool> EnableMaskedGatherScatters;
60 
61 extern cl::opt<unsigned> MVEMaxSupportedInterleaveFactor;
62 
63 /// Convert a vector load intrinsic into a simple llvm load instruction.
64 /// This is beneficial when the underlying object being addressed comes
65 /// from a constant, since we get constant-folding for free.
66 static Value *simplifyNeonVld1(const IntrinsicInst &II, unsigned MemAlign,
67                                InstCombiner::BuilderTy &Builder) {
68   auto *IntrAlign = dyn_cast<ConstantInt>(II.getArgOperand(1));
69 
70   if (!IntrAlign)
71     return nullptr;
72 
73   unsigned Alignment = IntrAlign->getLimitedValue() < MemAlign
74                            ? MemAlign
75                            : IntrAlign->getLimitedValue();
76 
77   if (!isPowerOf2_32(Alignment))
78     return nullptr;
79 
80   auto *BCastInst = Builder.CreateBitCast(II.getArgOperand(0),
81                                           PointerType::get(II.getType(), 0));
82   return Builder.CreateAlignedLoad(II.getType(), BCastInst, Align(Alignment));
83 }
84 
85 bool ARMTTIImpl::areInlineCompatible(const Function *Caller,
86                                      const Function *Callee) const {
87   const TargetMachine &TM = getTLI()->getTargetMachine();
88   const FeatureBitset &CallerBits =
89       TM.getSubtargetImpl(*Caller)->getFeatureBits();
90   const FeatureBitset &CalleeBits =
91       TM.getSubtargetImpl(*Callee)->getFeatureBits();
92 
93   // To inline a callee, all features not in the allowed list must match exactly.
94   bool MatchExact = (CallerBits & ~InlineFeaturesAllowed) ==
95                     (CalleeBits & ~InlineFeaturesAllowed);
96   // For features in the allowed list, the callee's features must be a subset of
97   // the callers'.
98   bool MatchSubset = ((CallerBits & CalleeBits) & InlineFeaturesAllowed) ==
99                      (CalleeBits & InlineFeaturesAllowed);
100   return MatchExact && MatchSubset;
101 }
102 
103 bool ARMTTIImpl::shouldFavorBackedgeIndex(const Loop *L) const {
104   if (L->getHeader()->getParent()->hasOptSize())
105     return false;
106   if (ST->hasMVEIntegerOps())
107     return false;
108   return ST->isMClass() && ST->isThumb2() && L->getNumBlocks() == 1;
109 }
110 
111 bool ARMTTIImpl::shouldFavorPostInc() const {
112   if (ST->hasMVEIntegerOps())
113     return true;
114   return false;
115 }
116 
117 Optional<Instruction *>
118 ARMTTIImpl::instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const {
119   using namespace PatternMatch;
120   Intrinsic::ID IID = II.getIntrinsicID();
121   switch (IID) {
122   default:
123     break;
124   case Intrinsic::arm_neon_vld1: {
125     Align MemAlign =
126         getKnownAlignment(II.getArgOperand(0), IC.getDataLayout(), &II,
127                           &IC.getAssumptionCache(), &IC.getDominatorTree());
128     if (Value *V = simplifyNeonVld1(II, MemAlign.value(), IC.Builder)) {
129       return IC.replaceInstUsesWith(II, V);
130     }
131     break;
132   }
133 
134   case Intrinsic::arm_neon_vld2:
135   case Intrinsic::arm_neon_vld3:
136   case Intrinsic::arm_neon_vld4:
137   case Intrinsic::arm_neon_vld2lane:
138   case Intrinsic::arm_neon_vld3lane:
139   case Intrinsic::arm_neon_vld4lane:
140   case Intrinsic::arm_neon_vst1:
141   case Intrinsic::arm_neon_vst2:
142   case Intrinsic::arm_neon_vst3:
143   case Intrinsic::arm_neon_vst4:
144   case Intrinsic::arm_neon_vst2lane:
145   case Intrinsic::arm_neon_vst3lane:
146   case Intrinsic::arm_neon_vst4lane: {
147     Align MemAlign =
148         getKnownAlignment(II.getArgOperand(0), IC.getDataLayout(), &II,
149                           &IC.getAssumptionCache(), &IC.getDominatorTree());
150     unsigned AlignArg = II.getNumArgOperands() - 1;
151     Value *AlignArgOp = II.getArgOperand(AlignArg);
152     MaybeAlign Align = cast<ConstantInt>(AlignArgOp)->getMaybeAlignValue();
153     if (Align && *Align < MemAlign) {
154       return IC.replaceOperand(
155           II, AlignArg,
156           ConstantInt::get(Type::getInt32Ty(II.getContext()), MemAlign.value(),
157                            false));
158     }
159     break;
160   }
161 
162   case Intrinsic::arm_mve_pred_i2v: {
163     Value *Arg = II.getArgOperand(0);
164     Value *ArgArg;
165     if (match(Arg, PatternMatch::m_Intrinsic<Intrinsic::arm_mve_pred_v2i>(
166                        PatternMatch::m_Value(ArgArg))) &&
167         II.getType() == ArgArg->getType()) {
168       return IC.replaceInstUsesWith(II, ArgArg);
169     }
170     Constant *XorMask;
171     if (match(Arg, m_Xor(PatternMatch::m_Intrinsic<Intrinsic::arm_mve_pred_v2i>(
172                              PatternMatch::m_Value(ArgArg)),
173                          PatternMatch::m_Constant(XorMask))) &&
174         II.getType() == ArgArg->getType()) {
175       if (auto *CI = dyn_cast<ConstantInt>(XorMask)) {
176         if (CI->getValue().trunc(16).isAllOnesValue()) {
177           auto TrueVector = IC.Builder.CreateVectorSplat(
178               cast<FixedVectorType>(II.getType())->getNumElements(),
179               IC.Builder.getTrue());
180           return BinaryOperator::Create(Instruction::Xor, ArgArg, TrueVector);
181         }
182       }
183     }
184     KnownBits ScalarKnown(32);
185     if (IC.SimplifyDemandedBits(&II, 0, APInt::getLowBitsSet(32, 16),
186                                 ScalarKnown, 0)) {
187       return &II;
188     }
189     break;
190   }
191   case Intrinsic::arm_mve_pred_v2i: {
192     Value *Arg = II.getArgOperand(0);
193     Value *ArgArg;
194     if (match(Arg, PatternMatch::m_Intrinsic<Intrinsic::arm_mve_pred_i2v>(
195                        PatternMatch::m_Value(ArgArg)))) {
196       return IC.replaceInstUsesWith(II, ArgArg);
197     }
198     if (!II.getMetadata(LLVMContext::MD_range)) {
199       Type *IntTy32 = Type::getInt32Ty(II.getContext());
200       Metadata *M[] = {
201           ConstantAsMetadata::get(ConstantInt::get(IntTy32, 0)),
202           ConstantAsMetadata::get(ConstantInt::get(IntTy32, 0xFFFF))};
203       II.setMetadata(LLVMContext::MD_range, MDNode::get(II.getContext(), M));
204       return &II;
205     }
206     break;
207   }
208   case Intrinsic::arm_mve_vadc:
209   case Intrinsic::arm_mve_vadc_predicated: {
210     unsigned CarryOp =
211         (II.getIntrinsicID() == Intrinsic::arm_mve_vadc_predicated) ? 3 : 2;
212     assert(II.getArgOperand(CarryOp)->getType()->getScalarSizeInBits() == 32 &&
213            "Bad type for intrinsic!");
214 
215     KnownBits CarryKnown(32);
216     if (IC.SimplifyDemandedBits(&II, CarryOp, APInt::getOneBitSet(32, 29),
217                                 CarryKnown)) {
218       return &II;
219     }
220     break;
221   }
222   case Intrinsic::arm_mve_vmldava: {
223     Instruction *I = cast<Instruction>(&II);
224     if (I->hasOneUse()) {
225       auto *User = cast<Instruction>(*I->user_begin());
226       Value *OpZ;
227       if (match(User, m_c_Add(m_Specific(I), m_Value(OpZ))) &&
228           match(I->getOperand(3), m_Zero())) {
229         Value *OpX = I->getOperand(4);
230         Value *OpY = I->getOperand(5);
231         Type *OpTy = OpX->getType();
232 
233         IC.Builder.SetInsertPoint(User);
234         Value *V =
235             IC.Builder.CreateIntrinsic(Intrinsic::arm_mve_vmldava, {OpTy},
236                                        {I->getOperand(0), I->getOperand(1),
237                                         I->getOperand(2), OpZ, OpX, OpY});
238 
239         IC.replaceInstUsesWith(*User, V);
240         return IC.eraseInstFromFunction(*User);
241       }
242     }
243     return None;
244   }
245   }
246   return None;
247 }
248 
249 int ARMTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty,
250                               TTI::TargetCostKind CostKind) {
251   assert(Ty->isIntegerTy());
252 
253  unsigned Bits = Ty->getPrimitiveSizeInBits();
254  if (Bits == 0 || Imm.getActiveBits() >= 64)
255    return 4;
256 
257   int64_t SImmVal = Imm.getSExtValue();
258   uint64_t ZImmVal = Imm.getZExtValue();
259   if (!ST->isThumb()) {
260     if ((SImmVal >= 0 && SImmVal < 65536) ||
261         (ARM_AM::getSOImmVal(ZImmVal) != -1) ||
262         (ARM_AM::getSOImmVal(~ZImmVal) != -1))
263       return 1;
264     return ST->hasV6T2Ops() ? 2 : 3;
265   }
266   if (ST->isThumb2()) {
267     if ((SImmVal >= 0 && SImmVal < 65536) ||
268         (ARM_AM::getT2SOImmVal(ZImmVal) != -1) ||
269         (ARM_AM::getT2SOImmVal(~ZImmVal) != -1))
270       return 1;
271     return ST->hasV6T2Ops() ? 2 : 3;
272   }
273   // Thumb1, any i8 imm cost 1.
274   if (Bits == 8 || (SImmVal >= 0 && SImmVal < 256))
275     return 1;
276   if ((~SImmVal < 256) || ARM_AM::isThumbImmShiftedVal(ZImmVal))
277     return 2;
278   // Load from constantpool.
279   return 3;
280 }
281 
282 // Constants smaller than 256 fit in the immediate field of
283 // Thumb1 instructions so we return a zero cost and 1 otherwise.
284 int ARMTTIImpl::getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx,
285                                       const APInt &Imm, Type *Ty) {
286   if (Imm.isNonNegative() && Imm.getLimitedValue() < 256)
287     return 0;
288 
289   return 1;
290 }
291 
292 // Checks whether Inst is part of a min(max()) or max(min()) pattern
293 // that will match to an SSAT instruction
294 static bool isSSATMinMaxPattern(Instruction *Inst, const APInt &Imm) {
295   Value *LHS, *RHS;
296   ConstantInt *C;
297   SelectPatternFlavor InstSPF = matchSelectPattern(Inst, LHS, RHS).Flavor;
298 
299   if (InstSPF == SPF_SMAX &&
300       PatternMatch::match(RHS, PatternMatch::m_ConstantInt(C)) &&
301       C->getValue() == Imm && Imm.isNegative() && (-Imm).isPowerOf2()) {
302 
303     auto isSSatMin = [&](Value *MinInst) {
304       if (isa<SelectInst>(MinInst)) {
305         Value *MinLHS, *MinRHS;
306         ConstantInt *MinC;
307         SelectPatternFlavor MinSPF =
308             matchSelectPattern(MinInst, MinLHS, MinRHS).Flavor;
309         if (MinSPF == SPF_SMIN &&
310             PatternMatch::match(MinRHS, PatternMatch::m_ConstantInt(MinC)) &&
311             MinC->getValue() == ((-Imm) - 1))
312           return true;
313       }
314       return false;
315     };
316 
317     if (isSSatMin(Inst->getOperand(1)) ||
318         (Inst->hasNUses(2) && (isSSatMin(*Inst->user_begin()) ||
319                                isSSatMin(*(++Inst->user_begin())))))
320       return true;
321   }
322   return false;
323 }
324 
325 int ARMTTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx,
326                                   const APInt &Imm, Type *Ty,
327                                   TTI::TargetCostKind CostKind,
328                                   Instruction *Inst) {
329   // Division by a constant can be turned into multiplication, but only if we
330   // know it's constant. So it's not so much that the immediate is cheap (it's
331   // not), but that the alternative is worse.
332   // FIXME: this is probably unneeded with GlobalISel.
333   if ((Opcode == Instruction::SDiv || Opcode == Instruction::UDiv ||
334        Opcode == Instruction::SRem || Opcode == Instruction::URem) &&
335       Idx == 1)
336     return 0;
337 
338   if (Opcode == Instruction::And) {
339     // UXTB/UXTH
340     if (Imm == 255 || Imm == 65535)
341       return 0;
342     // Conversion to BIC is free, and means we can use ~Imm instead.
343     return std::min(getIntImmCost(Imm, Ty, CostKind),
344                     getIntImmCost(~Imm, Ty, CostKind));
345   }
346 
347   if (Opcode == Instruction::Add)
348     // Conversion to SUB is free, and means we can use -Imm instead.
349     return std::min(getIntImmCost(Imm, Ty, CostKind),
350                     getIntImmCost(-Imm, Ty, CostKind));
351 
352   if (Opcode == Instruction::ICmp && Imm.isNegative() &&
353       Ty->getIntegerBitWidth() == 32) {
354     int64_t NegImm = -Imm.getSExtValue();
355     if (ST->isThumb2() && NegImm < 1<<12)
356       // icmp X, #-C -> cmn X, #C
357       return 0;
358     if (ST->isThumb() && NegImm < 1<<8)
359       // icmp X, #-C -> adds X, #C
360       return 0;
361   }
362 
363   // xor a, -1 can always be folded to MVN
364   if (Opcode == Instruction::Xor && Imm.isAllOnesValue())
365     return 0;
366 
367   // Ensures negative constant of min(max()) or max(min()) patterns that
368   // match to SSAT instructions don't get hoisted
369   if (Inst && ((ST->hasV6Ops() && !ST->isThumb()) || ST->isThumb2()) &&
370       Ty->getIntegerBitWidth() <= 32) {
371     if (isSSATMinMaxPattern(Inst, Imm) ||
372         (isa<ICmpInst>(Inst) && Inst->hasOneUse() &&
373          isSSATMinMaxPattern(cast<Instruction>(*Inst->user_begin()), Imm)))
374       return 0;
375   }
376 
377   return getIntImmCost(Imm, Ty, CostKind);
378 }
379 
380 int ARMTTIImpl::getCFInstrCost(unsigned Opcode, TTI::TargetCostKind CostKind) {
381   if (CostKind == TTI::TCK_RecipThroughput &&
382       (ST->hasNEON() || ST->hasMVEIntegerOps())) {
383     // FIXME: The vectorizer is highly sensistive to the cost of these
384     // instructions, which suggests that it may be using the costs incorrectly.
385     // But, for now, just make them free to avoid performance regressions for
386     // vector targets.
387     return 0;
388   }
389   return BaseT::getCFInstrCost(Opcode, CostKind);
390 }
391 
392 int ARMTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
393                                  TTI::CastContextHint CCH,
394                                  TTI::TargetCostKind CostKind,
395                                  const Instruction *I) {
396   int ISD = TLI->InstructionOpcodeToISD(Opcode);
397   assert(ISD && "Invalid opcode");
398 
399   // TODO: Allow non-throughput costs that aren't binary.
400   auto AdjustCost = [&CostKind](int Cost) {
401     if (CostKind != TTI::TCK_RecipThroughput)
402       return Cost == 0 ? 0 : 1;
403     return Cost;
404   };
405   auto IsLegalFPType = [this](EVT VT) {
406     EVT EltVT = VT.getScalarType();
407     return (EltVT == MVT::f32 && ST->hasVFP2Base()) ||
408             (EltVT == MVT::f64 && ST->hasFP64()) ||
409             (EltVT == MVT::f16 && ST->hasFullFP16());
410   };
411 
412   EVT SrcTy = TLI->getValueType(DL, Src);
413   EVT DstTy = TLI->getValueType(DL, Dst);
414 
415   if (!SrcTy.isSimple() || !DstTy.isSimple())
416     return AdjustCost(
417         BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I));
418 
419   // Extending masked load/Truncating masked stores is expensive because we
420   // currently don't split them. This means that we'll likely end up
421   // loading/storing each element individually (hence the high cost).
422   if ((ST->hasMVEIntegerOps() &&
423        (Opcode == Instruction::Trunc || Opcode == Instruction::ZExt ||
424         Opcode == Instruction::SExt)) ||
425       (ST->hasMVEFloatOps() &&
426        (Opcode == Instruction::FPExt || Opcode == Instruction::FPTrunc) &&
427        IsLegalFPType(SrcTy) && IsLegalFPType(DstTy)))
428     if (CCH == TTI::CastContextHint::Masked && DstTy.getSizeInBits() > 128)
429       return 2 * DstTy.getVectorNumElements() * ST->getMVEVectorCostFactor();
430 
431   // The extend of other kinds of load is free
432   if (CCH == TTI::CastContextHint::Normal ||
433       CCH == TTI::CastContextHint::Masked) {
434     static const TypeConversionCostTblEntry LoadConversionTbl[] = {
435         {ISD::SIGN_EXTEND, MVT::i32, MVT::i16, 0},
436         {ISD::ZERO_EXTEND, MVT::i32, MVT::i16, 0},
437         {ISD::SIGN_EXTEND, MVT::i32, MVT::i8, 0},
438         {ISD::ZERO_EXTEND, MVT::i32, MVT::i8, 0},
439         {ISD::SIGN_EXTEND, MVT::i16, MVT::i8, 0},
440         {ISD::ZERO_EXTEND, MVT::i16, MVT::i8, 0},
441         {ISD::SIGN_EXTEND, MVT::i64, MVT::i32, 1},
442         {ISD::ZERO_EXTEND, MVT::i64, MVT::i32, 1},
443         {ISD::SIGN_EXTEND, MVT::i64, MVT::i16, 1},
444         {ISD::ZERO_EXTEND, MVT::i64, MVT::i16, 1},
445         {ISD::SIGN_EXTEND, MVT::i64, MVT::i8, 1},
446         {ISD::ZERO_EXTEND, MVT::i64, MVT::i8, 1},
447     };
448     if (const auto *Entry = ConvertCostTableLookup(
449             LoadConversionTbl, ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
450       return AdjustCost(Entry->Cost);
451 
452     static const TypeConversionCostTblEntry MVELoadConversionTbl[] = {
453         {ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 0},
454         {ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 0},
455         {ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 0},
456         {ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 0},
457         {ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 0},
458         {ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 0},
459         // The following extend from a legal type to an illegal type, so need to
460         // split the load. This introduced an extra load operation, but the
461         // extend is still "free".
462         {ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i16, 1},
463         {ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i16, 1},
464         {ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 3},
465         {ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 3},
466         {ISD::SIGN_EXTEND, MVT::v16i16, MVT::v16i8, 1},
467         {ISD::ZERO_EXTEND, MVT::v16i16, MVT::v16i8, 1},
468     };
469     if (SrcTy.isVector() && ST->hasMVEIntegerOps()) {
470       if (const auto *Entry =
471               ConvertCostTableLookup(MVELoadConversionTbl, ISD,
472                                      DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
473         return AdjustCost(Entry->Cost * ST->getMVEVectorCostFactor());
474     }
475 
476     static const TypeConversionCostTblEntry MVEFLoadConversionTbl[] = {
477         // FPExtends are similar but also require the VCVT instructions.
478         {ISD::FP_EXTEND, MVT::v4f32, MVT::v4f16, 1},
479         {ISD::FP_EXTEND, MVT::v8f32, MVT::v8f16, 3},
480     };
481     if (SrcTy.isVector() && ST->hasMVEFloatOps()) {
482       if (const auto *Entry =
483               ConvertCostTableLookup(MVEFLoadConversionTbl, ISD,
484                                      DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
485         return AdjustCost(Entry->Cost * ST->getMVEVectorCostFactor());
486     }
487 
488     // The truncate of a store is free. This is the mirror of extends above.
489     static const TypeConversionCostTblEntry MVEStoreConversionTbl[] = {
490         {ISD::TRUNCATE, MVT::v4i32, MVT::v4i16, 0},
491         {ISD::TRUNCATE, MVT::v4i32, MVT::v4i8, 0},
492         {ISD::TRUNCATE, MVT::v8i16, MVT::v8i8, 0},
493         {ISD::TRUNCATE, MVT::v8i32, MVT::v8i16, 1},
494         {ISD::TRUNCATE, MVT::v16i32, MVT::v16i8, 3},
495         {ISD::TRUNCATE, MVT::v16i16, MVT::v16i8, 1},
496     };
497     if (SrcTy.isVector() && ST->hasMVEIntegerOps()) {
498       if (const auto *Entry =
499               ConvertCostTableLookup(MVEStoreConversionTbl, ISD,
500                                      SrcTy.getSimpleVT(), DstTy.getSimpleVT()))
501         return AdjustCost(Entry->Cost * ST->getMVEVectorCostFactor());
502     }
503 
504     static const TypeConversionCostTblEntry MVEFStoreConversionTbl[] = {
505         {ISD::FP_ROUND, MVT::v4f32, MVT::v4f16, 1},
506         {ISD::FP_ROUND, MVT::v8f32, MVT::v8f16, 3},
507     };
508     if (SrcTy.isVector() && ST->hasMVEFloatOps()) {
509       if (const auto *Entry =
510               ConvertCostTableLookup(MVEFStoreConversionTbl, ISD,
511                                      SrcTy.getSimpleVT(), DstTy.getSimpleVT()))
512         return AdjustCost(Entry->Cost * ST->getMVEVectorCostFactor());
513     }
514   }
515 
516   // NEON vector operations that can extend their inputs.
517   if ((ISD == ISD::SIGN_EXTEND || ISD == ISD::ZERO_EXTEND) &&
518       I && I->hasOneUse() && ST->hasNEON() && SrcTy.isVector()) {
519     static const TypeConversionCostTblEntry NEONDoubleWidthTbl[] = {
520       // vaddl
521       { ISD::ADD, MVT::v4i32, MVT::v4i16, 0 },
522       { ISD::ADD, MVT::v8i16, MVT::v8i8,  0 },
523       // vsubl
524       { ISD::SUB, MVT::v4i32, MVT::v4i16, 0 },
525       { ISD::SUB, MVT::v8i16, MVT::v8i8,  0 },
526       // vmull
527       { ISD::MUL, MVT::v4i32, MVT::v4i16, 0 },
528       { ISD::MUL, MVT::v8i16, MVT::v8i8,  0 },
529       // vshll
530       { ISD::SHL, MVT::v4i32, MVT::v4i16, 0 },
531       { ISD::SHL, MVT::v8i16, MVT::v8i8,  0 },
532     };
533 
534     auto *User = cast<Instruction>(*I->user_begin());
535     int UserISD = TLI->InstructionOpcodeToISD(User->getOpcode());
536     if (auto *Entry = ConvertCostTableLookup(NEONDoubleWidthTbl, UserISD,
537                                              DstTy.getSimpleVT(),
538                                              SrcTy.getSimpleVT())) {
539       return AdjustCost(Entry->Cost);
540     }
541   }
542 
543   // Single to/from double precision conversions.
544   if (Src->isVectorTy() && ST->hasNEON() &&
545       ((ISD == ISD::FP_ROUND && SrcTy.getScalarType() == MVT::f64 &&
546         DstTy.getScalarType() == MVT::f32) ||
547        (ISD == ISD::FP_EXTEND && SrcTy.getScalarType() == MVT::f32 &&
548         DstTy.getScalarType() == MVT::f64))) {
549     static const CostTblEntry NEONFltDblTbl[] = {
550         // Vector fptrunc/fpext conversions.
551         {ISD::FP_ROUND, MVT::v2f64, 2},
552         {ISD::FP_EXTEND, MVT::v2f32, 2},
553         {ISD::FP_EXTEND, MVT::v4f32, 4}};
554 
555     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
556     if (const auto *Entry = CostTableLookup(NEONFltDblTbl, ISD, LT.second))
557       return AdjustCost(LT.first * Entry->Cost);
558   }
559 
560   // Some arithmetic, load and store operations have specific instructions
561   // to cast up/down their types automatically at no extra cost.
562   // TODO: Get these tables to know at least what the related operations are.
563   static const TypeConversionCostTblEntry NEONVectorConversionTbl[] = {
564     { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
565     { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
566     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i32, 1 },
567     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i32, 1 },
568     { ISD::TRUNCATE,    MVT::v4i32, MVT::v4i64, 0 },
569     { ISD::TRUNCATE,    MVT::v4i16, MVT::v4i32, 1 },
570 
571     // The number of vmovl instructions for the extension.
572     { ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8,  1 },
573     { ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8,  1 },
574     { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8,  2 },
575     { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8,  2 },
576     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i8,  3 },
577     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i8,  3 },
578     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i16, 2 },
579     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i16, 2 },
580     { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
581     { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
582     { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i8, 3 },
583     { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i8, 3 },
584     { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i8, 7 },
585     { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i8, 7 },
586     { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i16, 6 },
587     { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i16, 6 },
588     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
589     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
590 
591     // Operations that we legalize using splitting.
592     { ISD::TRUNCATE,    MVT::v16i8, MVT::v16i32, 6 },
593     { ISD::TRUNCATE,    MVT::v8i8, MVT::v8i32, 3 },
594 
595     // Vector float <-> i32 conversions.
596     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i32, 1 },
597     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i32, 1 },
598 
599     { ISD::SINT_TO_FP,  MVT::v2f32, MVT::v2i8, 3 },
600     { ISD::UINT_TO_FP,  MVT::v2f32, MVT::v2i8, 3 },
601     { ISD::SINT_TO_FP,  MVT::v2f32, MVT::v2i16, 2 },
602     { ISD::UINT_TO_FP,  MVT::v2f32, MVT::v2i16, 2 },
603     { ISD::SINT_TO_FP,  MVT::v2f32, MVT::v2i32, 1 },
604     { ISD::UINT_TO_FP,  MVT::v2f32, MVT::v2i32, 1 },
605     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i1, 3 },
606     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i1, 3 },
607     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i8, 3 },
608     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i8, 3 },
609     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i16, 2 },
610     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i16, 2 },
611     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i16, 4 },
612     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i16, 4 },
613     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i32, 2 },
614     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i32, 2 },
615     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i16, 8 },
616     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i16, 8 },
617     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i32, 4 },
618     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i32, 4 },
619 
620     { ISD::FP_TO_SINT,  MVT::v4i32, MVT::v4f32, 1 },
621     { ISD::FP_TO_UINT,  MVT::v4i32, MVT::v4f32, 1 },
622     { ISD::FP_TO_SINT,  MVT::v4i8, MVT::v4f32, 3 },
623     { ISD::FP_TO_UINT,  MVT::v4i8, MVT::v4f32, 3 },
624     { ISD::FP_TO_SINT,  MVT::v4i16, MVT::v4f32, 2 },
625     { ISD::FP_TO_UINT,  MVT::v4i16, MVT::v4f32, 2 },
626 
627     // Vector double <-> i32 conversions.
628     { ISD::SINT_TO_FP,  MVT::v2f64, MVT::v2i32, 2 },
629     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i32, 2 },
630 
631     { ISD::SINT_TO_FP,  MVT::v2f64, MVT::v2i8, 4 },
632     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i8, 4 },
633     { ISD::SINT_TO_FP,  MVT::v2f64, MVT::v2i16, 3 },
634     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i16, 3 },
635     { ISD::SINT_TO_FP,  MVT::v2f64, MVT::v2i32, 2 },
636     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i32, 2 },
637 
638     { ISD::FP_TO_SINT,  MVT::v2i32, MVT::v2f64, 2 },
639     { ISD::FP_TO_UINT,  MVT::v2i32, MVT::v2f64, 2 },
640     { ISD::FP_TO_SINT,  MVT::v8i16, MVT::v8f32, 4 },
641     { ISD::FP_TO_UINT,  MVT::v8i16, MVT::v8f32, 4 },
642     { ISD::FP_TO_SINT,  MVT::v16i16, MVT::v16f32, 8 },
643     { ISD::FP_TO_UINT,  MVT::v16i16, MVT::v16f32, 8 }
644   };
645 
646   if (SrcTy.isVector() && ST->hasNEON()) {
647     if (const auto *Entry = ConvertCostTableLookup(NEONVectorConversionTbl, ISD,
648                                                    DstTy.getSimpleVT(),
649                                                    SrcTy.getSimpleVT()))
650       return AdjustCost(Entry->Cost);
651   }
652 
653   // Scalar float to integer conversions.
654   static const TypeConversionCostTblEntry NEONFloatConversionTbl[] = {
655     { ISD::FP_TO_SINT,  MVT::i1, MVT::f32, 2 },
656     { ISD::FP_TO_UINT,  MVT::i1, MVT::f32, 2 },
657     { ISD::FP_TO_SINT,  MVT::i1, MVT::f64, 2 },
658     { ISD::FP_TO_UINT,  MVT::i1, MVT::f64, 2 },
659     { ISD::FP_TO_SINT,  MVT::i8, MVT::f32, 2 },
660     { ISD::FP_TO_UINT,  MVT::i8, MVT::f32, 2 },
661     { ISD::FP_TO_SINT,  MVT::i8, MVT::f64, 2 },
662     { ISD::FP_TO_UINT,  MVT::i8, MVT::f64, 2 },
663     { ISD::FP_TO_SINT,  MVT::i16, MVT::f32, 2 },
664     { ISD::FP_TO_UINT,  MVT::i16, MVT::f32, 2 },
665     { ISD::FP_TO_SINT,  MVT::i16, MVT::f64, 2 },
666     { ISD::FP_TO_UINT,  MVT::i16, MVT::f64, 2 },
667     { ISD::FP_TO_SINT,  MVT::i32, MVT::f32, 2 },
668     { ISD::FP_TO_UINT,  MVT::i32, MVT::f32, 2 },
669     { ISD::FP_TO_SINT,  MVT::i32, MVT::f64, 2 },
670     { ISD::FP_TO_UINT,  MVT::i32, MVT::f64, 2 },
671     { ISD::FP_TO_SINT,  MVT::i64, MVT::f32, 10 },
672     { ISD::FP_TO_UINT,  MVT::i64, MVT::f32, 10 },
673     { ISD::FP_TO_SINT,  MVT::i64, MVT::f64, 10 },
674     { ISD::FP_TO_UINT,  MVT::i64, MVT::f64, 10 }
675   };
676   if (SrcTy.isFloatingPoint() && ST->hasNEON()) {
677     if (const auto *Entry = ConvertCostTableLookup(NEONFloatConversionTbl, ISD,
678                                                    DstTy.getSimpleVT(),
679                                                    SrcTy.getSimpleVT()))
680       return AdjustCost(Entry->Cost);
681   }
682 
683   // Scalar integer to float conversions.
684   static const TypeConversionCostTblEntry NEONIntegerConversionTbl[] = {
685     { ISD::SINT_TO_FP,  MVT::f32, MVT::i1, 2 },
686     { ISD::UINT_TO_FP,  MVT::f32, MVT::i1, 2 },
687     { ISD::SINT_TO_FP,  MVT::f64, MVT::i1, 2 },
688     { ISD::UINT_TO_FP,  MVT::f64, MVT::i1, 2 },
689     { ISD::SINT_TO_FP,  MVT::f32, MVT::i8, 2 },
690     { ISD::UINT_TO_FP,  MVT::f32, MVT::i8, 2 },
691     { ISD::SINT_TO_FP,  MVT::f64, MVT::i8, 2 },
692     { ISD::UINT_TO_FP,  MVT::f64, MVT::i8, 2 },
693     { ISD::SINT_TO_FP,  MVT::f32, MVT::i16, 2 },
694     { ISD::UINT_TO_FP,  MVT::f32, MVT::i16, 2 },
695     { ISD::SINT_TO_FP,  MVT::f64, MVT::i16, 2 },
696     { ISD::UINT_TO_FP,  MVT::f64, MVT::i16, 2 },
697     { ISD::SINT_TO_FP,  MVT::f32, MVT::i32, 2 },
698     { ISD::UINT_TO_FP,  MVT::f32, MVT::i32, 2 },
699     { ISD::SINT_TO_FP,  MVT::f64, MVT::i32, 2 },
700     { ISD::UINT_TO_FP,  MVT::f64, MVT::i32, 2 },
701     { ISD::SINT_TO_FP,  MVT::f32, MVT::i64, 10 },
702     { ISD::UINT_TO_FP,  MVT::f32, MVT::i64, 10 },
703     { ISD::SINT_TO_FP,  MVT::f64, MVT::i64, 10 },
704     { ISD::UINT_TO_FP,  MVT::f64, MVT::i64, 10 }
705   };
706 
707   if (SrcTy.isInteger() && ST->hasNEON()) {
708     if (const auto *Entry = ConvertCostTableLookup(NEONIntegerConversionTbl,
709                                                    ISD, DstTy.getSimpleVT(),
710                                                    SrcTy.getSimpleVT()))
711       return AdjustCost(Entry->Cost);
712   }
713 
714   // MVE extend costs, taken from codegen tests. i8->i16 or i16->i32 is one
715   // instruction, i8->i32 is two. i64 zexts are an VAND with a constant, sext
716   // are linearised so take more.
717   static const TypeConversionCostTblEntry MVEVectorConversionTbl[] = {
718     { ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
719     { ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
720     { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 2 },
721     { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 2 },
722     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i8, 10 },
723     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i8, 2 },
724     { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
725     { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
726     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i16, 10 },
727     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i16, 2 },
728     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i32, 8 },
729     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i32, 2 },
730   };
731 
732   if (SrcTy.isVector() && ST->hasMVEIntegerOps()) {
733     if (const auto *Entry = ConvertCostTableLookup(MVEVectorConversionTbl,
734                                                    ISD, DstTy.getSimpleVT(),
735                                                    SrcTy.getSimpleVT()))
736       return AdjustCost(Entry->Cost * ST->getMVEVectorCostFactor());
737   }
738 
739   if (ISD == ISD::FP_ROUND || ISD == ISD::FP_EXTEND) {
740     // As general rule, fp converts that were not matched above are scalarized
741     // and cost 1 vcvt for each lane, so long as the instruction is available.
742     // If not it will become a series of function calls.
743     const int CallCost = getCallInstrCost(nullptr, Dst, {Src}, CostKind);
744     int Lanes = 1;
745     if (SrcTy.isFixedLengthVector())
746       Lanes = SrcTy.getVectorNumElements();
747 
748     if (IsLegalFPType(SrcTy) && IsLegalFPType(DstTy))
749       return Lanes;
750     else
751       return Lanes * CallCost;
752   }
753 
754   // Scalar integer conversion costs.
755   static const TypeConversionCostTblEntry ARMIntegerConversionTbl[] = {
756     // i16 -> i64 requires two dependent operations.
757     { ISD::SIGN_EXTEND, MVT::i64, MVT::i16, 2 },
758 
759     // Truncates on i64 are assumed to be free.
760     { ISD::TRUNCATE,    MVT::i32, MVT::i64, 0 },
761     { ISD::TRUNCATE,    MVT::i16, MVT::i64, 0 },
762     { ISD::TRUNCATE,    MVT::i8,  MVT::i64, 0 },
763     { ISD::TRUNCATE,    MVT::i1,  MVT::i64, 0 }
764   };
765 
766   if (SrcTy.isInteger()) {
767     if (const auto *Entry = ConvertCostTableLookup(ARMIntegerConversionTbl, ISD,
768                                                    DstTy.getSimpleVT(),
769                                                    SrcTy.getSimpleVT()))
770       return AdjustCost(Entry->Cost);
771   }
772 
773   int BaseCost = ST->hasMVEIntegerOps() && Src->isVectorTy()
774                      ? ST->getMVEVectorCostFactor()
775                      : 1;
776   return AdjustCost(
777       BaseCost * BaseT::getCastInstrCost(Opcode, Dst, Src, CCH, CostKind, I));
778 }
779 
780 int ARMTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy,
781                                    unsigned Index) {
782   // Penalize inserting into an D-subregister. We end up with a three times
783   // lower estimated throughput on swift.
784   if (ST->hasSlowLoadDSubregister() && Opcode == Instruction::InsertElement &&
785       ValTy->isVectorTy() && ValTy->getScalarSizeInBits() <= 32)
786     return 3;
787 
788   if (ST->hasNEON() && (Opcode == Instruction::InsertElement ||
789                         Opcode == Instruction::ExtractElement)) {
790     // Cross-class copies are expensive on many microarchitectures,
791     // so assume they are expensive by default.
792     if (cast<VectorType>(ValTy)->getElementType()->isIntegerTy())
793       return 3;
794 
795     // Even if it's not a cross class copy, this likely leads to mixing
796     // of NEON and VFP code and should be therefore penalized.
797     if (ValTy->isVectorTy() &&
798         ValTy->getScalarSizeInBits() <= 32)
799       return std::max(BaseT::getVectorInstrCost(Opcode, ValTy, Index), 2U);
800   }
801 
802   if (ST->hasMVEIntegerOps() && (Opcode == Instruction::InsertElement ||
803                                  Opcode == Instruction::ExtractElement)) {
804     // We say MVE moves costs at least the MVEVectorCostFactor, even though
805     // they are scalar instructions. This helps prevent mixing scalar and
806     // vector, to prevent vectorising where we end up just scalarising the
807     // result anyway.
808     return std::max(BaseT::getVectorInstrCost(Opcode, ValTy, Index),
809                     ST->getMVEVectorCostFactor()) *
810            cast<FixedVectorType>(ValTy)->getNumElements() / 2;
811   }
812 
813   return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
814 }
815 
816 int ARMTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
817                                    CmpInst::Predicate VecPred,
818                                    TTI::TargetCostKind CostKind,
819                                    const Instruction *I) {
820   int ISD = TLI->InstructionOpcodeToISD(Opcode);
821 
822   // Thumb scalar code size cost for select.
823   if (CostKind == TTI::TCK_CodeSize && ISD == ISD::SELECT &&
824       ST->isThumb() && !ValTy->isVectorTy()) {
825     // Assume expensive structs.
826     if (TLI->getValueType(DL, ValTy, true) == MVT::Other)
827       return TTI::TCC_Expensive;
828 
829     // Select costs can vary because they:
830     // - may require one or more conditional mov (including an IT),
831     // - can't operate directly on immediates,
832     // - require live flags, which we can't copy around easily.
833     int Cost = TLI->getTypeLegalizationCost(DL, ValTy).first;
834 
835     // Possible IT instruction for Thumb2, or more for Thumb1.
836     ++Cost;
837 
838     // i1 values may need rematerialising by using mov immediates and/or
839     // flag setting instructions.
840     if (ValTy->isIntegerTy(1))
841       ++Cost;
842 
843     return Cost;
844   }
845 
846   // On NEON a vector select gets lowered to vbsl.
847   if (ST->hasNEON() && ValTy->isVectorTy() && ISD == ISD::SELECT && CondTy) {
848     // Lowering of some vector selects is currently far from perfect.
849     static const TypeConversionCostTblEntry NEONVectorSelectTbl[] = {
850       { ISD::SELECT, MVT::v4i1, MVT::v4i64, 4*4 + 1*2 + 1 },
851       { ISD::SELECT, MVT::v8i1, MVT::v8i64, 50 },
852       { ISD::SELECT, MVT::v16i1, MVT::v16i64, 100 }
853     };
854 
855     EVT SelCondTy = TLI->getValueType(DL, CondTy);
856     EVT SelValTy = TLI->getValueType(DL, ValTy);
857     if (SelCondTy.isSimple() && SelValTy.isSimple()) {
858       if (const auto *Entry = ConvertCostTableLookup(NEONVectorSelectTbl, ISD,
859                                                      SelCondTy.getSimpleVT(),
860                                                      SelValTy.getSimpleVT()))
861         return Entry->Cost;
862     }
863 
864     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
865     return LT.first;
866   }
867 
868   // Default to cheap (throughput/size of 1 instruction) but adjust throughput
869   // for "multiple beats" potentially needed by MVE instructions.
870   int BaseCost = 1;
871   if (CostKind != TTI::TCK_CodeSize && ST->hasMVEIntegerOps() &&
872       ValTy->isVectorTy())
873     BaseCost = ST->getMVEVectorCostFactor();
874 
875   return BaseCost *
876          BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, VecPred, CostKind, I);
877 }
878 
879 int ARMTTIImpl::getAddressComputationCost(Type *Ty, ScalarEvolution *SE,
880                                           const SCEV *Ptr) {
881   // Address computations in vectorized code with non-consecutive addresses will
882   // likely result in more instructions compared to scalar code where the
883   // computation can more often be merged into the index mode. The resulting
884   // extra micro-ops can significantly decrease throughput.
885   unsigned NumVectorInstToHideOverhead = 10;
886   int MaxMergeDistance = 64;
887 
888   if (ST->hasNEON()) {
889     if (Ty->isVectorTy() && SE &&
890         !BaseT::isConstantStridedAccessLessThan(SE, Ptr, MaxMergeDistance + 1))
891       return NumVectorInstToHideOverhead;
892 
893     // In many cases the address computation is not merged into the instruction
894     // addressing mode.
895     return 1;
896   }
897   return BaseT::getAddressComputationCost(Ty, SE, Ptr);
898 }
899 
900 bool ARMTTIImpl::isProfitableLSRChainElement(Instruction *I) {
901   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
902     // If a VCTP is part of a chain, it's already profitable and shouldn't be
903     // optimized, else LSR may block tail-predication.
904     switch (II->getIntrinsicID()) {
905     case Intrinsic::arm_mve_vctp8:
906     case Intrinsic::arm_mve_vctp16:
907     case Intrinsic::arm_mve_vctp32:
908     case Intrinsic::arm_mve_vctp64:
909       return true;
910     default:
911       break;
912     }
913   }
914   return false;
915 }
916 
917 bool ARMTTIImpl::isLegalMaskedLoad(Type *DataTy, Align Alignment) {
918   if (!EnableMaskedLoadStores || !ST->hasMVEIntegerOps())
919     return false;
920 
921   if (auto *VecTy = dyn_cast<FixedVectorType>(DataTy)) {
922     // Don't support v2i1 yet.
923     if (VecTy->getNumElements() == 2)
924       return false;
925 
926     // We don't support extending fp types.
927      unsigned VecWidth = DataTy->getPrimitiveSizeInBits();
928     if (VecWidth != 128 && VecTy->getElementType()->isFloatingPointTy())
929       return false;
930   }
931 
932   unsigned EltWidth = DataTy->getScalarSizeInBits();
933   return (EltWidth == 32 && Alignment >= 4) ||
934          (EltWidth == 16 && Alignment >= 2) || (EltWidth == 8);
935 }
936 
937 bool ARMTTIImpl::isLegalMaskedGather(Type *Ty, Align Alignment) {
938   if (!EnableMaskedGatherScatters || !ST->hasMVEIntegerOps())
939     return false;
940 
941   // This method is called in 2 places:
942   //  - from the vectorizer with a scalar type, in which case we need to get
943   //  this as good as we can with the limited info we have (and rely on the cost
944   //  model for the rest).
945   //  - from the masked intrinsic lowering pass with the actual vector type.
946   // For MVE, we have a custom lowering pass that will already have custom
947   // legalised any gathers that we can to MVE intrinsics, and want to expand all
948   // the rest. The pass runs before the masked intrinsic lowering pass, so if we
949   // are here, we know we want to expand.
950   if (isa<VectorType>(Ty))
951     return false;
952 
953   unsigned EltWidth = Ty->getScalarSizeInBits();
954   return ((EltWidth == 32 && Alignment >= 4) ||
955           (EltWidth == 16 && Alignment >= 2) || EltWidth == 8);
956 }
957 
958 /// Given a memcpy/memset/memmove instruction, return the number of memory
959 /// operations performed, via querying findOptimalMemOpLowering. Returns -1 if a
960 /// call is used.
961 int ARMTTIImpl::getNumMemOps(const IntrinsicInst *I) const {
962   MemOp MOp;
963   unsigned DstAddrSpace = ~0u;
964   unsigned SrcAddrSpace = ~0u;
965   const Function *F = I->getParent()->getParent();
966 
967   if (const auto *MC = dyn_cast<MemTransferInst>(I)) {
968     ConstantInt *C = dyn_cast<ConstantInt>(MC->getLength());
969     // If 'size' is not a constant, a library call will be generated.
970     if (!C)
971       return -1;
972 
973     const unsigned Size = C->getValue().getZExtValue();
974     const Align DstAlign = *MC->getDestAlign();
975     const Align SrcAlign = *MC->getSourceAlign();
976 
977     MOp = MemOp::Copy(Size, /*DstAlignCanChange*/ false, DstAlign, SrcAlign,
978                       /*IsVolatile*/ false);
979     DstAddrSpace = MC->getDestAddressSpace();
980     SrcAddrSpace = MC->getSourceAddressSpace();
981   }
982   else if (const auto *MS = dyn_cast<MemSetInst>(I)) {
983     ConstantInt *C = dyn_cast<ConstantInt>(MS->getLength());
984     // If 'size' is not a constant, a library call will be generated.
985     if (!C)
986       return -1;
987 
988     const unsigned Size = C->getValue().getZExtValue();
989     const Align DstAlign = *MS->getDestAlign();
990 
991     MOp = MemOp::Set(Size, /*DstAlignCanChange*/ false, DstAlign,
992                      /*IsZeroMemset*/ false, /*IsVolatile*/ false);
993     DstAddrSpace = MS->getDestAddressSpace();
994   }
995   else
996     llvm_unreachable("Expected a memcpy/move or memset!");
997 
998   unsigned Limit, Factor = 2;
999   switch(I->getIntrinsicID()) {
1000     case Intrinsic::memcpy:
1001       Limit = TLI->getMaxStoresPerMemcpy(F->hasMinSize());
1002       break;
1003     case Intrinsic::memmove:
1004       Limit = TLI->getMaxStoresPerMemmove(F->hasMinSize());
1005       break;
1006     case Intrinsic::memset:
1007       Limit = TLI->getMaxStoresPerMemset(F->hasMinSize());
1008       Factor = 1;
1009       break;
1010     default:
1011       llvm_unreachable("Expected a memcpy/move or memset!");
1012   }
1013 
1014   // MemOps will be poplulated with a list of data types that needs to be
1015   // loaded and stored. That's why we multiply the number of elements by 2 to
1016   // get the cost for this memcpy.
1017   std::vector<EVT> MemOps;
1018   if (getTLI()->findOptimalMemOpLowering(
1019           MemOps, Limit, MOp, DstAddrSpace,
1020           SrcAddrSpace, F->getAttributes()))
1021     return MemOps.size() * Factor;
1022 
1023   // If we can't find an optimal memop lowering, return the default cost
1024   return -1;
1025 }
1026 
1027 int ARMTTIImpl::getMemcpyCost(const Instruction *I) {
1028   int NumOps = getNumMemOps(cast<IntrinsicInst>(I));
1029 
1030   // To model the cost of a library call, we assume 1 for the call, and
1031   // 3 for the argument setup.
1032   if (NumOps == -1)
1033     return 4;
1034   return NumOps;
1035 }
1036 
1037 int ARMTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, VectorType *Tp,
1038                                int Index, VectorType *SubTp) {
1039   if (ST->hasNEON()) {
1040     if (Kind == TTI::SK_Broadcast) {
1041       static const CostTblEntry NEONDupTbl[] = {
1042           // VDUP handles these cases.
1043           {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
1044           {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
1045           {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
1046           {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
1047           {ISD::VECTOR_SHUFFLE, MVT::v4i16, 1},
1048           {ISD::VECTOR_SHUFFLE, MVT::v8i8, 1},
1049 
1050           {ISD::VECTOR_SHUFFLE, MVT::v4i32, 1},
1051           {ISD::VECTOR_SHUFFLE, MVT::v4f32, 1},
1052           {ISD::VECTOR_SHUFFLE, MVT::v8i16, 1},
1053           {ISD::VECTOR_SHUFFLE, MVT::v16i8, 1}};
1054 
1055       std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
1056 
1057       if (const auto *Entry =
1058               CostTableLookup(NEONDupTbl, ISD::VECTOR_SHUFFLE, LT.second))
1059         return LT.first * Entry->Cost;
1060     }
1061     if (Kind == TTI::SK_Reverse) {
1062       static const CostTblEntry NEONShuffleTbl[] = {
1063           // Reverse shuffle cost one instruction if we are shuffling within a
1064           // double word (vrev) or two if we shuffle a quad word (vrev, vext).
1065           {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
1066           {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
1067           {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
1068           {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
1069           {ISD::VECTOR_SHUFFLE, MVT::v4i16, 1},
1070           {ISD::VECTOR_SHUFFLE, MVT::v8i8, 1},
1071 
1072           {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2},
1073           {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2},
1074           {ISD::VECTOR_SHUFFLE, MVT::v8i16, 2},
1075           {ISD::VECTOR_SHUFFLE, MVT::v16i8, 2}};
1076 
1077       std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
1078 
1079       if (const auto *Entry =
1080               CostTableLookup(NEONShuffleTbl, ISD::VECTOR_SHUFFLE, LT.second))
1081         return LT.first * Entry->Cost;
1082     }
1083     if (Kind == TTI::SK_Select) {
1084       static const CostTblEntry NEONSelShuffleTbl[] = {
1085           // Select shuffle cost table for ARM. Cost is the number of
1086           // instructions
1087           // required to create the shuffled vector.
1088 
1089           {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
1090           {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
1091           {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
1092           {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
1093 
1094           {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2},
1095           {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2},
1096           {ISD::VECTOR_SHUFFLE, MVT::v4i16, 2},
1097 
1098           {ISD::VECTOR_SHUFFLE, MVT::v8i16, 16},
1099 
1100           {ISD::VECTOR_SHUFFLE, MVT::v16i8, 32}};
1101 
1102       std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
1103       if (const auto *Entry = CostTableLookup(NEONSelShuffleTbl,
1104                                               ISD::VECTOR_SHUFFLE, LT.second))
1105         return LT.first * Entry->Cost;
1106     }
1107   }
1108   if (ST->hasMVEIntegerOps()) {
1109     if (Kind == TTI::SK_Broadcast) {
1110       static const CostTblEntry MVEDupTbl[] = {
1111           // VDUP handles these cases.
1112           {ISD::VECTOR_SHUFFLE, MVT::v4i32, 1},
1113           {ISD::VECTOR_SHUFFLE, MVT::v8i16, 1},
1114           {ISD::VECTOR_SHUFFLE, MVT::v16i8, 1},
1115           {ISD::VECTOR_SHUFFLE, MVT::v4f32, 1},
1116           {ISD::VECTOR_SHUFFLE, MVT::v8f16, 1}};
1117 
1118       std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
1119 
1120       if (const auto *Entry = CostTableLookup(MVEDupTbl, ISD::VECTOR_SHUFFLE,
1121                                               LT.second))
1122         return LT.first * Entry->Cost * ST->getMVEVectorCostFactor();
1123     }
1124   }
1125   int BaseCost = ST->hasMVEIntegerOps() && Tp->isVectorTy()
1126                      ? ST->getMVEVectorCostFactor()
1127                      : 1;
1128   return BaseCost * BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
1129 }
1130 
1131 int ARMTTIImpl::getArithmeticInstrCost(unsigned Opcode, Type *Ty,
1132                                        TTI::TargetCostKind CostKind,
1133                                        TTI::OperandValueKind Op1Info,
1134                                        TTI::OperandValueKind Op2Info,
1135                                        TTI::OperandValueProperties Opd1PropInfo,
1136                                        TTI::OperandValueProperties Opd2PropInfo,
1137                                        ArrayRef<const Value *> Args,
1138                                        const Instruction *CxtI) {
1139   int ISDOpcode = TLI->InstructionOpcodeToISD(Opcode);
1140   if (ST->isThumb() && CostKind == TTI::TCK_CodeSize && Ty->isIntegerTy(1)) {
1141     // Make operations on i1 relatively expensive as this often involves
1142     // combining predicates. AND and XOR should be easier to handle with IT
1143     // blocks.
1144     switch (ISDOpcode) {
1145     default:
1146       break;
1147     case ISD::AND:
1148     case ISD::XOR:
1149       return 2;
1150     case ISD::OR:
1151       return 3;
1152     }
1153   }
1154 
1155   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
1156 
1157   if (ST->hasNEON()) {
1158     const unsigned FunctionCallDivCost = 20;
1159     const unsigned ReciprocalDivCost = 10;
1160     static const CostTblEntry CostTbl[] = {
1161       // Division.
1162       // These costs are somewhat random. Choose a cost of 20 to indicate that
1163       // vectorizing devision (added function call) is going to be very expensive.
1164       // Double registers types.
1165       { ISD::SDIV, MVT::v1i64, 1 * FunctionCallDivCost},
1166       { ISD::UDIV, MVT::v1i64, 1 * FunctionCallDivCost},
1167       { ISD::SREM, MVT::v1i64, 1 * FunctionCallDivCost},
1168       { ISD::UREM, MVT::v1i64, 1 * FunctionCallDivCost},
1169       { ISD::SDIV, MVT::v2i32, 2 * FunctionCallDivCost},
1170       { ISD::UDIV, MVT::v2i32, 2 * FunctionCallDivCost},
1171       { ISD::SREM, MVT::v2i32, 2 * FunctionCallDivCost},
1172       { ISD::UREM, MVT::v2i32, 2 * FunctionCallDivCost},
1173       { ISD::SDIV, MVT::v4i16,     ReciprocalDivCost},
1174       { ISD::UDIV, MVT::v4i16,     ReciprocalDivCost},
1175       { ISD::SREM, MVT::v4i16, 4 * FunctionCallDivCost},
1176       { ISD::UREM, MVT::v4i16, 4 * FunctionCallDivCost},
1177       { ISD::SDIV, MVT::v8i8,      ReciprocalDivCost},
1178       { ISD::UDIV, MVT::v8i8,      ReciprocalDivCost},
1179       { ISD::SREM, MVT::v8i8,  8 * FunctionCallDivCost},
1180       { ISD::UREM, MVT::v8i8,  8 * FunctionCallDivCost},
1181       // Quad register types.
1182       { ISD::SDIV, MVT::v2i64, 2 * FunctionCallDivCost},
1183       { ISD::UDIV, MVT::v2i64, 2 * FunctionCallDivCost},
1184       { ISD::SREM, MVT::v2i64, 2 * FunctionCallDivCost},
1185       { ISD::UREM, MVT::v2i64, 2 * FunctionCallDivCost},
1186       { ISD::SDIV, MVT::v4i32, 4 * FunctionCallDivCost},
1187       { ISD::UDIV, MVT::v4i32, 4 * FunctionCallDivCost},
1188       { ISD::SREM, MVT::v4i32, 4 * FunctionCallDivCost},
1189       { ISD::UREM, MVT::v4i32, 4 * FunctionCallDivCost},
1190       { ISD::SDIV, MVT::v8i16, 8 * FunctionCallDivCost},
1191       { ISD::UDIV, MVT::v8i16, 8 * FunctionCallDivCost},
1192       { ISD::SREM, MVT::v8i16, 8 * FunctionCallDivCost},
1193       { ISD::UREM, MVT::v8i16, 8 * FunctionCallDivCost},
1194       { ISD::SDIV, MVT::v16i8, 16 * FunctionCallDivCost},
1195       { ISD::UDIV, MVT::v16i8, 16 * FunctionCallDivCost},
1196       { ISD::SREM, MVT::v16i8, 16 * FunctionCallDivCost},
1197       { ISD::UREM, MVT::v16i8, 16 * FunctionCallDivCost},
1198       // Multiplication.
1199     };
1200 
1201     if (const auto *Entry = CostTableLookup(CostTbl, ISDOpcode, LT.second))
1202       return LT.first * Entry->Cost;
1203 
1204     int Cost = BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
1205                                              Op2Info,
1206                                              Opd1PropInfo, Opd2PropInfo);
1207 
1208     // This is somewhat of a hack. The problem that we are facing is that SROA
1209     // creates a sequence of shift, and, or instructions to construct values.
1210     // These sequences are recognized by the ISel and have zero-cost. Not so for
1211     // the vectorized code. Because we have support for v2i64 but not i64 those
1212     // sequences look particularly beneficial to vectorize.
1213     // To work around this we increase the cost of v2i64 operations to make them
1214     // seem less beneficial.
1215     if (LT.second == MVT::v2i64 &&
1216         Op2Info == TargetTransformInfo::OK_UniformConstantValue)
1217       Cost += 4;
1218 
1219     return Cost;
1220   }
1221 
1222   // If this operation is a shift on arm/thumb2, it might well be folded into
1223   // the following instruction, hence having a cost of 0.
1224   auto LooksLikeAFreeShift = [&]() {
1225     if (ST->isThumb1Only() || Ty->isVectorTy())
1226       return false;
1227 
1228     if (!CxtI || !CxtI->hasOneUse() || !CxtI->isShift())
1229       return false;
1230     if (Op2Info != TargetTransformInfo::OK_UniformConstantValue)
1231       return false;
1232 
1233     // Folded into a ADC/ADD/AND/BIC/CMP/EOR/MVN/ORR/ORN/RSB/SBC/SUB
1234     switch (cast<Instruction>(CxtI->user_back())->getOpcode()) {
1235     case Instruction::Add:
1236     case Instruction::Sub:
1237     case Instruction::And:
1238     case Instruction::Xor:
1239     case Instruction::Or:
1240     case Instruction::ICmp:
1241       return true;
1242     default:
1243       return false;
1244     }
1245   };
1246   if (LooksLikeAFreeShift())
1247     return 0;
1248 
1249   // Default to cheap (throughput/size of 1 instruction) but adjust throughput
1250   // for "multiple beats" potentially needed by MVE instructions.
1251   int BaseCost = 1;
1252   if (CostKind != TTI::TCK_CodeSize && ST->hasMVEIntegerOps() &&
1253       Ty->isVectorTy())
1254     BaseCost = ST->getMVEVectorCostFactor();
1255 
1256   // The rest of this mostly follows what is done in BaseT::getArithmeticInstrCost,
1257   // without treating floats as more expensive that scalars or increasing the
1258   // costs for custom operations. The results is also multiplied by the
1259   // MVEVectorCostFactor where appropriate.
1260   if (TLI->isOperationLegalOrCustomOrPromote(ISDOpcode, LT.second))
1261     return LT.first * BaseCost;
1262 
1263   // Else this is expand, assume that we need to scalarize this op.
1264   if (auto *VTy = dyn_cast<FixedVectorType>(Ty)) {
1265     unsigned Num = VTy->getNumElements();
1266     unsigned Cost = getArithmeticInstrCost(Opcode, Ty->getScalarType(),
1267                                            CostKind);
1268     // Return the cost of multiple scalar invocation plus the cost of
1269     // inserting and extracting the values.
1270     return BaseT::getScalarizationOverhead(VTy, Args) + Num * Cost;
1271   }
1272 
1273   return BaseCost;
1274 }
1275 
1276 int ARMTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
1277                                 MaybeAlign Alignment, unsigned AddressSpace,
1278                                 TTI::TargetCostKind CostKind,
1279                                 const Instruction *I) {
1280   // TODO: Handle other cost kinds.
1281   if (CostKind != TTI::TCK_RecipThroughput)
1282     return 1;
1283 
1284   // Type legalization can't handle structs
1285   if (TLI->getValueType(DL, Src, true) == MVT::Other)
1286     return BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
1287                                   CostKind);
1288 
1289   if (ST->hasNEON() && Src->isVectorTy() &&
1290       (Alignment && *Alignment != Align(16)) &&
1291       cast<VectorType>(Src)->getElementType()->isDoubleTy()) {
1292     // Unaligned loads/stores are extremely inefficient.
1293     // We need 4 uops for vst.1/vld.1 vs 1uop for vldr/vstr.
1294     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
1295     return LT.first * 4;
1296   }
1297 
1298   // MVE can optimize a fpext(load(4xhalf)) using an extending integer load.
1299   // Same for stores.
1300   if (ST->hasMVEFloatOps() && isa<FixedVectorType>(Src) && I &&
1301       ((Opcode == Instruction::Load && I->hasOneUse() &&
1302         isa<FPExtInst>(*I->user_begin())) ||
1303        (Opcode == Instruction::Store && isa<FPTruncInst>(I->getOperand(0))))) {
1304     FixedVectorType *SrcVTy = cast<FixedVectorType>(Src);
1305     Type *DstTy =
1306         Opcode == Instruction::Load
1307             ? (*I->user_begin())->getType()
1308             : cast<Instruction>(I->getOperand(0))->getOperand(0)->getType();
1309     if (SrcVTy->getNumElements() == 4 && SrcVTy->getScalarType()->isHalfTy() &&
1310         DstTy->getScalarType()->isFloatTy())
1311       return ST->getMVEVectorCostFactor();
1312   }
1313 
1314   int BaseCost = ST->hasMVEIntegerOps() && Src->isVectorTy()
1315                      ? ST->getMVEVectorCostFactor()
1316                      : 1;
1317   return BaseCost * BaseT::getMemoryOpCost(Opcode, Src, Alignment, AddressSpace,
1318                                            CostKind, I);
1319 }
1320 
1321 int ARMTTIImpl::getInterleavedMemoryOpCost(
1322     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
1323     Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind,
1324     bool UseMaskForCond, bool UseMaskForGaps) {
1325   assert(Factor >= 2 && "Invalid interleave factor");
1326   assert(isa<VectorType>(VecTy) && "Expect a vector type");
1327 
1328   // vldN/vstN doesn't support vector types of i64/f64 element.
1329   bool EltIs64Bits = DL.getTypeSizeInBits(VecTy->getScalarType()) == 64;
1330 
1331   if (Factor <= TLI->getMaxSupportedInterleaveFactor() && !EltIs64Bits &&
1332       !UseMaskForCond && !UseMaskForGaps) {
1333     unsigned NumElts = cast<FixedVectorType>(VecTy)->getNumElements();
1334     auto *SubVecTy =
1335         FixedVectorType::get(VecTy->getScalarType(), NumElts / Factor);
1336 
1337     // vldN/vstN only support legal vector types of size 64 or 128 in bits.
1338     // Accesses having vector types that are a multiple of 128 bits can be
1339     // matched to more than one vldN/vstN instruction.
1340     int BaseCost = ST->hasMVEIntegerOps() ? ST->getMVEVectorCostFactor() : 1;
1341     if (NumElts % Factor == 0 &&
1342         TLI->isLegalInterleavedAccessType(Factor, SubVecTy, DL))
1343       return Factor * BaseCost * TLI->getNumInterleavedAccesses(SubVecTy, DL);
1344 
1345     // Some smaller than legal interleaved patterns are cheap as we can make
1346     // use of the vmovn or vrev patterns to interleave a standard load. This is
1347     // true for v4i8, v8i8 and v4i16 at least (but not for v4f16 as it is
1348     // promoted differently). The cost of 2 here is then a load and vrev or
1349     // vmovn.
1350     if (ST->hasMVEIntegerOps() && Factor == 2 && NumElts / Factor > 2 &&
1351         VecTy->isIntOrIntVectorTy() &&
1352         DL.getTypeSizeInBits(SubVecTy).getFixedSize() <= 64)
1353       return 2 * BaseCost;
1354   }
1355 
1356   return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
1357                                            Alignment, AddressSpace, CostKind,
1358                                            UseMaskForCond, UseMaskForGaps);
1359 }
1360 
1361 unsigned ARMTTIImpl::getGatherScatterOpCost(unsigned Opcode, Type *DataTy,
1362                                             const Value *Ptr, bool VariableMask,
1363                                             Align Alignment,
1364                                             TTI::TargetCostKind CostKind,
1365                                             const Instruction *I) {
1366   using namespace PatternMatch;
1367   if (!ST->hasMVEIntegerOps() || !EnableMaskedGatherScatters)
1368     return BaseT::getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
1369                                          Alignment, CostKind, I);
1370 
1371   assert(DataTy->isVectorTy() && "Can't do gather/scatters on scalar!");
1372   auto *VTy = cast<FixedVectorType>(DataTy);
1373 
1374   // TODO: Splitting, once we do that.
1375 
1376   unsigned NumElems = VTy->getNumElements();
1377   unsigned EltSize = VTy->getScalarSizeInBits();
1378   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, DataTy);
1379 
1380   // For now, it is assumed that for the MVE gather instructions the loads are
1381   // all effectively serialised. This means the cost is the scalar cost
1382   // multiplied by the number of elements being loaded. This is possibly very
1383   // conservative, but even so we still end up vectorising loops because the
1384   // cost per iteration for many loops is lower than for scalar loops.
1385   unsigned VectorCost = NumElems * LT.first * ST->getMVEVectorCostFactor();
1386   // The scalarization cost should be a lot higher. We use the number of vector
1387   // elements plus the scalarization overhead.
1388   unsigned ScalarCost =
1389       NumElems * LT.first + BaseT::getScalarizationOverhead(VTy, {});
1390 
1391   if (EltSize < 8 || Alignment < EltSize / 8)
1392     return ScalarCost;
1393 
1394   unsigned ExtSize = EltSize;
1395   // Check whether there's a single user that asks for an extended type
1396   if (I != nullptr) {
1397     // Dependent of the caller of this function, a gather instruction will
1398     // either have opcode Instruction::Load or be a call to the masked_gather
1399     // intrinsic
1400     if ((I->getOpcode() == Instruction::Load ||
1401          match(I, m_Intrinsic<Intrinsic::masked_gather>())) &&
1402         I->hasOneUse()) {
1403       const User *Us = *I->users().begin();
1404       if (isa<ZExtInst>(Us) || isa<SExtInst>(Us)) {
1405         // only allow valid type combinations
1406         unsigned TypeSize =
1407             cast<Instruction>(Us)->getType()->getScalarSizeInBits();
1408         if (((TypeSize == 32 && (EltSize == 8 || EltSize == 16)) ||
1409              (TypeSize == 16 && EltSize == 8)) &&
1410             TypeSize * NumElems == 128) {
1411           ExtSize = TypeSize;
1412         }
1413       }
1414     }
1415     // Check whether the input data needs to be truncated
1416     TruncInst *T;
1417     if ((I->getOpcode() == Instruction::Store ||
1418          match(I, m_Intrinsic<Intrinsic::masked_scatter>())) &&
1419         (T = dyn_cast<TruncInst>(I->getOperand(0)))) {
1420       // Only allow valid type combinations
1421       unsigned TypeSize = T->getOperand(0)->getType()->getScalarSizeInBits();
1422       if (((EltSize == 16 && TypeSize == 32) ||
1423            (EltSize == 8 && (TypeSize == 32 || TypeSize == 16))) &&
1424           TypeSize * NumElems == 128)
1425         ExtSize = TypeSize;
1426     }
1427   }
1428 
1429   if (ExtSize * NumElems != 128 || NumElems < 4)
1430     return ScalarCost;
1431 
1432   // Any (aligned) i32 gather will not need to be scalarised.
1433   if (ExtSize == 32)
1434     return VectorCost;
1435   // For smaller types, we need to ensure that the gep's inputs are correctly
1436   // extended from a small enough value. Other sizes (including i64) are
1437   // scalarized for now.
1438   if (ExtSize != 8 && ExtSize != 16)
1439     return ScalarCost;
1440 
1441   if (const auto *BC = dyn_cast<BitCastInst>(Ptr))
1442     Ptr = BC->getOperand(0);
1443   if (const auto *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
1444     if (GEP->getNumOperands() != 2)
1445       return ScalarCost;
1446     unsigned Scale = DL.getTypeAllocSize(GEP->getResultElementType());
1447     // Scale needs to be correct (which is only relevant for i16s).
1448     if (Scale != 1 && Scale * 8 != ExtSize)
1449       return ScalarCost;
1450     // And we need to zext (not sext) the indexes from a small enough type.
1451     if (const auto *ZExt = dyn_cast<ZExtInst>(GEP->getOperand(1))) {
1452       if (ZExt->getOperand(0)->getType()->getScalarSizeInBits() <= ExtSize)
1453         return VectorCost;
1454     }
1455     return ScalarCost;
1456   }
1457   return ScalarCost;
1458 }
1459 
1460 int ARMTTIImpl::getArithmeticReductionCost(unsigned Opcode, VectorType *ValTy,
1461                                            bool IsPairwiseForm,
1462                                            TTI::TargetCostKind CostKind) {
1463   EVT ValVT = TLI->getValueType(DL, ValTy);
1464   int ISD = TLI->InstructionOpcodeToISD(Opcode);
1465   if (!ST->hasMVEIntegerOps() || !ValVT.isSimple() || ISD != ISD::ADD)
1466     return BaseT::getArithmeticReductionCost(Opcode, ValTy, IsPairwiseForm,
1467                                              CostKind);
1468 
1469   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
1470 
1471   static const CostTblEntry CostTblAdd[]{
1472       {ISD::ADD, MVT::v16i8, 1},
1473       {ISD::ADD, MVT::v8i16, 1},
1474       {ISD::ADD, MVT::v4i32, 1},
1475   };
1476   if (const auto *Entry = CostTableLookup(CostTblAdd, ISD, LT.second))
1477     return Entry->Cost * ST->getMVEVectorCostFactor() * LT.first;
1478 
1479   return BaseT::getArithmeticReductionCost(Opcode, ValTy, IsPairwiseForm,
1480                                            CostKind);
1481 }
1482 
1483 int ARMTTIImpl::getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA,
1484                                       TTI::TargetCostKind CostKind) {
1485   // Currently we make a somewhat optimistic assumption that active_lane_mask's
1486   // are always free. In reality it may be freely folded into a tail predicated
1487   // loop, expanded into a VCPT or expanded into a lot of add/icmp code. We
1488   // may need to improve this in the future, but being able to detect if it
1489   // is free or not involves looking at a lot of other code. We currently assume
1490   // that the vectorizer inserted these, and knew what it was doing in adding
1491   // one.
1492   if (ST->hasMVEIntegerOps() && ICA.getID() == Intrinsic::get_active_lane_mask)
1493     return 0;
1494 
1495   return BaseT::getIntrinsicInstrCost(ICA, CostKind);
1496 }
1497 
1498 bool ARMTTIImpl::isLoweredToCall(const Function *F) {
1499   if (!F->isIntrinsic())
1500     BaseT::isLoweredToCall(F);
1501 
1502   // Assume all Arm-specific intrinsics map to an instruction.
1503   if (F->getName().startswith("llvm.arm"))
1504     return false;
1505 
1506   switch (F->getIntrinsicID()) {
1507   default: break;
1508   case Intrinsic::powi:
1509   case Intrinsic::sin:
1510   case Intrinsic::cos:
1511   case Intrinsic::pow:
1512   case Intrinsic::log:
1513   case Intrinsic::log10:
1514   case Intrinsic::log2:
1515   case Intrinsic::exp:
1516   case Intrinsic::exp2:
1517     return true;
1518   case Intrinsic::sqrt:
1519   case Intrinsic::fabs:
1520   case Intrinsic::copysign:
1521   case Intrinsic::floor:
1522   case Intrinsic::ceil:
1523   case Intrinsic::trunc:
1524   case Intrinsic::rint:
1525   case Intrinsic::nearbyint:
1526   case Intrinsic::round:
1527   case Intrinsic::canonicalize:
1528   case Intrinsic::lround:
1529   case Intrinsic::llround:
1530   case Intrinsic::lrint:
1531   case Intrinsic::llrint:
1532     if (F->getReturnType()->isDoubleTy() && !ST->hasFP64())
1533       return true;
1534     if (F->getReturnType()->isHalfTy() && !ST->hasFullFP16())
1535       return true;
1536     // Some operations can be handled by vector instructions and assume
1537     // unsupported vectors will be expanded into supported scalar ones.
1538     // TODO Handle scalar operations properly.
1539     return !ST->hasFPARMv8Base() && !ST->hasVFP2Base();
1540   case Intrinsic::masked_store:
1541   case Intrinsic::masked_load:
1542   case Intrinsic::masked_gather:
1543   case Intrinsic::masked_scatter:
1544     return !ST->hasMVEIntegerOps();
1545   case Intrinsic::sadd_with_overflow:
1546   case Intrinsic::uadd_with_overflow:
1547   case Intrinsic::ssub_with_overflow:
1548   case Intrinsic::usub_with_overflow:
1549   case Intrinsic::sadd_sat:
1550   case Intrinsic::uadd_sat:
1551   case Intrinsic::ssub_sat:
1552   case Intrinsic::usub_sat:
1553     return false;
1554   }
1555 
1556   return BaseT::isLoweredToCall(F);
1557 }
1558 
1559 bool ARMTTIImpl::maybeLoweredToCall(Instruction &I) {
1560   unsigned ISD = TLI->InstructionOpcodeToISD(I.getOpcode());
1561   EVT VT = TLI->getValueType(DL, I.getType(), true);
1562   if (TLI->getOperationAction(ISD, VT) == TargetLowering::LibCall)
1563     return true;
1564 
1565   // Check if an intrinsic will be lowered to a call and assume that any
1566   // other CallInst will generate a bl.
1567   if (auto *Call = dyn_cast<CallInst>(&I)) {
1568     if (auto *II = dyn_cast<IntrinsicInst>(Call)) {
1569       switch(II->getIntrinsicID()) {
1570         case Intrinsic::memcpy:
1571         case Intrinsic::memset:
1572         case Intrinsic::memmove:
1573           return getNumMemOps(II) == -1;
1574         default:
1575           if (const Function *F = Call->getCalledFunction())
1576             return isLoweredToCall(F);
1577       }
1578     }
1579     return true;
1580   }
1581 
1582   // FPv5 provides conversions between integer, double-precision,
1583   // single-precision, and half-precision formats.
1584   switch (I.getOpcode()) {
1585   default:
1586     break;
1587   case Instruction::FPToSI:
1588   case Instruction::FPToUI:
1589   case Instruction::SIToFP:
1590   case Instruction::UIToFP:
1591   case Instruction::FPTrunc:
1592   case Instruction::FPExt:
1593     return !ST->hasFPARMv8Base();
1594   }
1595 
1596   // FIXME: Unfortunately the approach of checking the Operation Action does
1597   // not catch all cases of Legalization that use library calls. Our
1598   // Legalization step categorizes some transformations into library calls as
1599   // Custom, Expand or even Legal when doing type legalization. So for now
1600   // we have to special case for instance the SDIV of 64bit integers and the
1601   // use of floating point emulation.
1602   if (VT.isInteger() && VT.getSizeInBits() >= 64) {
1603     switch (ISD) {
1604     default:
1605       break;
1606     case ISD::SDIV:
1607     case ISD::UDIV:
1608     case ISD::SREM:
1609     case ISD::UREM:
1610     case ISD::SDIVREM:
1611     case ISD::UDIVREM:
1612       return true;
1613     }
1614   }
1615 
1616   // Assume all other non-float operations are supported.
1617   if (!VT.isFloatingPoint())
1618     return false;
1619 
1620   // We'll need a library call to handle most floats when using soft.
1621   if (TLI->useSoftFloat()) {
1622     switch (I.getOpcode()) {
1623     default:
1624       return true;
1625     case Instruction::Alloca:
1626     case Instruction::Load:
1627     case Instruction::Store:
1628     case Instruction::Select:
1629     case Instruction::PHI:
1630       return false;
1631     }
1632   }
1633 
1634   // We'll need a libcall to perform double precision operations on a single
1635   // precision only FPU.
1636   if (I.getType()->isDoubleTy() && !ST->hasFP64())
1637     return true;
1638 
1639   // Likewise for half precision arithmetic.
1640   if (I.getType()->isHalfTy() && !ST->hasFullFP16())
1641     return true;
1642 
1643   return false;
1644 }
1645 
1646 bool ARMTTIImpl::isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
1647                                           AssumptionCache &AC,
1648                                           TargetLibraryInfo *LibInfo,
1649                                           HardwareLoopInfo &HWLoopInfo) {
1650   // Low-overhead branches are only supported in the 'low-overhead branch'
1651   // extension of v8.1-m.
1652   if (!ST->hasLOB() || DisableLowOverheadLoops) {
1653     LLVM_DEBUG(dbgs() << "ARMHWLoops: Disabled\n");
1654     return false;
1655   }
1656 
1657   if (!SE.hasLoopInvariantBackedgeTakenCount(L)) {
1658     LLVM_DEBUG(dbgs() << "ARMHWLoops: No BETC\n");
1659     return false;
1660   }
1661 
1662   const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1663   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
1664     LLVM_DEBUG(dbgs() << "ARMHWLoops: Uncomputable BETC\n");
1665     return false;
1666   }
1667 
1668   const SCEV *TripCountSCEV =
1669     SE.getAddExpr(BackedgeTakenCount,
1670                   SE.getOne(BackedgeTakenCount->getType()));
1671 
1672   // We need to store the trip count in LR, a 32-bit register.
1673   if (SE.getUnsignedRangeMax(TripCountSCEV).getBitWidth() > 32) {
1674     LLVM_DEBUG(dbgs() << "ARMHWLoops: Trip count does not fit into 32bits\n");
1675     return false;
1676   }
1677 
1678   // Making a call will trash LR and clear LO_BRANCH_INFO, so there's little
1679   // point in generating a hardware loop if that's going to happen.
1680 
1681   auto IsHardwareLoopIntrinsic = [](Instruction &I) {
1682     if (auto *Call = dyn_cast<IntrinsicInst>(&I)) {
1683       switch (Call->getIntrinsicID()) {
1684       default:
1685         break;
1686       case Intrinsic::start_loop_iterations:
1687       case Intrinsic::test_set_loop_iterations:
1688       case Intrinsic::loop_decrement:
1689       case Intrinsic::loop_decrement_reg:
1690         return true;
1691       }
1692     }
1693     return false;
1694   };
1695 
1696   // Scan the instructions to see if there's any that we know will turn into a
1697   // call or if this loop is already a low-overhead loop or will become a tail
1698   // predicated loop.
1699   bool IsTailPredLoop = false;
1700   auto ScanLoop = [&](Loop *L) {
1701     for (auto *BB : L->getBlocks()) {
1702       for (auto &I : *BB) {
1703         if (maybeLoweredToCall(I) || IsHardwareLoopIntrinsic(I) ||
1704             isa<InlineAsm>(I)) {
1705           LLVM_DEBUG(dbgs() << "ARMHWLoops: Bad instruction: " << I << "\n");
1706           return false;
1707         }
1708         if (auto *II = dyn_cast<IntrinsicInst>(&I))
1709           IsTailPredLoop |=
1710               II->getIntrinsicID() == Intrinsic::get_active_lane_mask ||
1711               II->getIntrinsicID() == Intrinsic::arm_mve_vctp8 ||
1712               II->getIntrinsicID() == Intrinsic::arm_mve_vctp16 ||
1713               II->getIntrinsicID() == Intrinsic::arm_mve_vctp32 ||
1714               II->getIntrinsicID() == Intrinsic::arm_mve_vctp64;
1715       }
1716     }
1717     return true;
1718   };
1719 
1720   // Visit inner loops.
1721   for (auto Inner : *L)
1722     if (!ScanLoop(Inner))
1723       return false;
1724 
1725   if (!ScanLoop(L))
1726     return false;
1727 
1728   // TODO: Check whether the trip count calculation is expensive. If L is the
1729   // inner loop but we know it has a low trip count, calculating that trip
1730   // count (in the parent loop) may be detrimental.
1731 
1732   LLVMContext &C = L->getHeader()->getContext();
1733   HWLoopInfo.CounterInReg = true;
1734   HWLoopInfo.IsNestingLegal = false;
1735   HWLoopInfo.PerformEntryTest = AllowWLSLoops && !IsTailPredLoop;
1736   HWLoopInfo.CountType = Type::getInt32Ty(C);
1737   HWLoopInfo.LoopDecrement = ConstantInt::get(HWLoopInfo.CountType, 1);
1738   return true;
1739 }
1740 
1741 static bool canTailPredicateInstruction(Instruction &I, int &ICmpCount) {
1742   // We don't allow icmp's, and because we only look at single block loops,
1743   // we simply count the icmps, i.e. there should only be 1 for the backedge.
1744   if (isa<ICmpInst>(&I) && ++ICmpCount > 1)
1745     return false;
1746 
1747   if (isa<FCmpInst>(&I))
1748     return false;
1749 
1750   // We could allow extending/narrowing FP loads/stores, but codegen is
1751   // too inefficient so reject this for now.
1752   if (isa<FPExtInst>(&I) || isa<FPTruncInst>(&I))
1753     return false;
1754 
1755   // Extends have to be extending-loads
1756   if (isa<SExtInst>(&I) || isa<ZExtInst>(&I) )
1757     if (!I.getOperand(0)->hasOneUse() || !isa<LoadInst>(I.getOperand(0)))
1758       return false;
1759 
1760   // Truncs have to be narrowing-stores
1761   if (isa<TruncInst>(&I) )
1762     if (!I.hasOneUse() || !isa<StoreInst>(*I.user_begin()))
1763       return false;
1764 
1765   return true;
1766 }
1767 
1768 // To set up a tail-predicated loop, we need to know the total number of
1769 // elements processed by that loop. Thus, we need to determine the element
1770 // size and:
1771 // 1) it should be uniform for all operations in the vector loop, so we
1772 //    e.g. don't want any widening/narrowing operations.
1773 // 2) it should be smaller than i64s because we don't have vector operations
1774 //    that work on i64s.
1775 // 3) we don't want elements to be reversed or shuffled, to make sure the
1776 //    tail-predication masks/predicates the right lanes.
1777 //
1778 static bool canTailPredicateLoop(Loop *L, LoopInfo *LI, ScalarEvolution &SE,
1779                                  const DataLayout &DL,
1780                                  const LoopAccessInfo *LAI) {
1781   LLVM_DEBUG(dbgs() << "Tail-predication: checking allowed instructions\n");
1782 
1783   // If there are live-out values, it is probably a reduction. We can predicate
1784   // most reduction operations freely under MVE using a combination of
1785   // prefer-predicated-reduction-select and inloop reductions. We limit this to
1786   // floating point and integer reductions, but don't check for operators
1787   // specifically here. If the value ends up not being a reduction (and so the
1788   // vectorizer cannot tailfold the loop), we should fall back to standard
1789   // vectorization automatically.
1790   SmallVector< Instruction *, 8 > LiveOuts;
1791   LiveOuts = llvm::findDefsUsedOutsideOfLoop(L);
1792   bool ReductionsDisabled =
1793       EnableTailPredication == TailPredication::EnabledNoReductions ||
1794       EnableTailPredication == TailPredication::ForceEnabledNoReductions;
1795 
1796   for (auto *I : LiveOuts) {
1797     if (!I->getType()->isIntegerTy() && !I->getType()->isFloatTy() &&
1798         !I->getType()->isHalfTy()) {
1799       LLVM_DEBUG(dbgs() << "Don't tail-predicate loop with non-integer/float "
1800                            "live-out value\n");
1801       return false;
1802     }
1803     if (ReductionsDisabled) {
1804       LLVM_DEBUG(dbgs() << "Reductions not enabled\n");
1805       return false;
1806     }
1807   }
1808 
1809   // Next, check that all instructions can be tail-predicated.
1810   PredicatedScalarEvolution PSE = LAI->getPSE();
1811   SmallVector<Instruction *, 16> LoadStores;
1812   int ICmpCount = 0;
1813 
1814   for (BasicBlock *BB : L->blocks()) {
1815     for (Instruction &I : BB->instructionsWithoutDebug()) {
1816       if (isa<PHINode>(&I))
1817         continue;
1818       if (!canTailPredicateInstruction(I, ICmpCount)) {
1819         LLVM_DEBUG(dbgs() << "Instruction not allowed: "; I.dump());
1820         return false;
1821       }
1822 
1823       Type *T  = I.getType();
1824       if (T->isPointerTy())
1825         T = T->getPointerElementType();
1826 
1827       if (T->getScalarSizeInBits() > 32) {
1828         LLVM_DEBUG(dbgs() << "Unsupported Type: "; T->dump());
1829         return false;
1830       }
1831       if (isa<StoreInst>(I) || isa<LoadInst>(I)) {
1832         Value *Ptr = isa<LoadInst>(I) ? I.getOperand(0) : I.getOperand(1);
1833         int64_t NextStride = getPtrStride(PSE, Ptr, L);
1834         if (NextStride == 1) {
1835           // TODO: for now only allow consecutive strides of 1. We could support
1836           // other strides as long as it is uniform, but let's keep it simple
1837           // for now.
1838           continue;
1839         } else if (NextStride == -1 ||
1840                    (NextStride == 2 && MVEMaxSupportedInterleaveFactor >= 2) ||
1841                    (NextStride == 4 && MVEMaxSupportedInterleaveFactor >= 4)) {
1842           LLVM_DEBUG(dbgs()
1843                      << "Consecutive strides of 2 found, vld2/vstr2 can't "
1844                         "be tail-predicated\n.");
1845           return false;
1846           // TODO: don't tail predicate if there is a reversed load?
1847         } else if (EnableMaskedGatherScatters) {
1848           // Gather/scatters do allow loading from arbitrary strides, at
1849           // least if they are loop invariant.
1850           // TODO: Loop variant strides should in theory work, too, but
1851           // this requires further testing.
1852           const SCEV *PtrScev =
1853               replaceSymbolicStrideSCEV(PSE, llvm::ValueToValueMap(), Ptr);
1854           if (auto AR = dyn_cast<SCEVAddRecExpr>(PtrScev)) {
1855             const SCEV *Step = AR->getStepRecurrence(*PSE.getSE());
1856             if (PSE.getSE()->isLoopInvariant(Step, L))
1857               continue;
1858           }
1859         }
1860         LLVM_DEBUG(dbgs() << "Bad stride found, can't "
1861                              "tail-predicate\n.");
1862         return false;
1863       }
1864     }
1865   }
1866 
1867   LLVM_DEBUG(dbgs() << "tail-predication: all instructions allowed!\n");
1868   return true;
1869 }
1870 
1871 bool ARMTTIImpl::preferPredicateOverEpilogue(Loop *L, LoopInfo *LI,
1872                                              ScalarEvolution &SE,
1873                                              AssumptionCache &AC,
1874                                              TargetLibraryInfo *TLI,
1875                                              DominatorTree *DT,
1876                                              const LoopAccessInfo *LAI) {
1877   if (!EnableTailPredication) {
1878     LLVM_DEBUG(dbgs() << "Tail-predication not enabled.\n");
1879     return false;
1880   }
1881 
1882   // Creating a predicated vector loop is the first step for generating a
1883   // tail-predicated hardware loop, for which we need the MVE masked
1884   // load/stores instructions:
1885   if (!ST->hasMVEIntegerOps())
1886     return false;
1887 
1888   // For now, restrict this to single block loops.
1889   if (L->getNumBlocks() > 1) {
1890     LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: not a single block "
1891                          "loop.\n");
1892     return false;
1893   }
1894 
1895   assert(L->isInnermost() && "preferPredicateOverEpilogue: inner-loop expected");
1896 
1897   HardwareLoopInfo HWLoopInfo(L);
1898   if (!HWLoopInfo.canAnalyze(*LI)) {
1899     LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not "
1900                          "analyzable.\n");
1901     return false;
1902   }
1903 
1904   // This checks if we have the low-overhead branch architecture
1905   // extension, and if we will create a hardware-loop:
1906   if (!isHardwareLoopProfitable(L, SE, AC, TLI, HWLoopInfo)) {
1907     LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not "
1908                          "profitable.\n");
1909     return false;
1910   }
1911 
1912   if (!HWLoopInfo.isHardwareLoopCandidate(SE, *LI, *DT)) {
1913     LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not "
1914                          "a candidate.\n");
1915     return false;
1916   }
1917 
1918   return canTailPredicateLoop(L, LI, SE, DL, LAI);
1919 }
1920 
1921 bool ARMTTIImpl::emitGetActiveLaneMask() const {
1922   if (!ST->hasMVEIntegerOps() || !EnableTailPredication)
1923     return false;
1924 
1925   // Intrinsic @llvm.get.active.lane.mask is supported.
1926   // It is used in the MVETailPredication pass, which requires the number of
1927   // elements processed by this vector loop to setup the tail-predicated
1928   // loop.
1929   return true;
1930 }
1931 void ARMTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
1932                                          TTI::UnrollingPreferences &UP) {
1933   // Only currently enable these preferences for M-Class cores.
1934   if (!ST->isMClass())
1935     return BasicTTIImplBase::getUnrollingPreferences(L, SE, UP);
1936 
1937   // Disable loop unrolling for Oz and Os.
1938   UP.OptSizeThreshold = 0;
1939   UP.PartialOptSizeThreshold = 0;
1940   if (L->getHeader()->getParent()->hasOptSize())
1941     return;
1942 
1943   // Only enable on Thumb-2 targets.
1944   if (!ST->isThumb2())
1945     return;
1946 
1947   SmallVector<BasicBlock*, 4> ExitingBlocks;
1948   L->getExitingBlocks(ExitingBlocks);
1949   LLVM_DEBUG(dbgs() << "Loop has:\n"
1950                     << "Blocks: " << L->getNumBlocks() << "\n"
1951                     << "Exit blocks: " << ExitingBlocks.size() << "\n");
1952 
1953   // Only allow another exit other than the latch. This acts as an early exit
1954   // as it mirrors the profitability calculation of the runtime unroller.
1955   if (ExitingBlocks.size() > 2)
1956     return;
1957 
1958   // Limit the CFG of the loop body for targets with a branch predictor.
1959   // Allowing 4 blocks permits if-then-else diamonds in the body.
1960   if (ST->hasBranchPredictor() && L->getNumBlocks() > 4)
1961     return;
1962 
1963   // Don't unroll vectorized loops, including the remainder loop
1964   if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
1965     return;
1966 
1967   // Scan the loop: don't unroll loops with calls as this could prevent
1968   // inlining.
1969   unsigned Cost = 0;
1970   for (auto *BB : L->getBlocks()) {
1971     for (auto &I : *BB) {
1972       // Don't unroll vectorised loop. MVE does not benefit from it as much as
1973       // scalar code.
1974       if (I.getType()->isVectorTy())
1975         return;
1976 
1977       if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
1978         if (const Function *F = cast<CallBase>(I).getCalledFunction()) {
1979           if (!isLoweredToCall(F))
1980             continue;
1981         }
1982         return;
1983       }
1984 
1985       SmallVector<const Value*, 4> Operands(I.value_op_begin(),
1986                                             I.value_op_end());
1987       Cost +=
1988         getUserCost(&I, Operands, TargetTransformInfo::TCK_SizeAndLatency);
1989     }
1990   }
1991 
1992   LLVM_DEBUG(dbgs() << "Cost of loop: " << Cost << "\n");
1993 
1994   UP.Partial = true;
1995   UP.Runtime = true;
1996   UP.UpperBound = true;
1997   UP.UnrollRemainder = true;
1998   UP.DefaultUnrollRuntimeCount = 4;
1999   UP.UnrollAndJam = true;
2000   UP.UnrollAndJamInnerLoopThreshold = 60;
2001 
2002   // Force unrolling small loops can be very useful because of the branch
2003   // taken cost of the backedge.
2004   if (Cost < 12)
2005     UP.Force = true;
2006 }
2007 
2008 void ARMTTIImpl::getPeelingPreferences(Loop *L, ScalarEvolution &SE,
2009                                        TTI::PeelingPreferences &PP) {
2010   BaseT::getPeelingPreferences(L, SE, PP);
2011 }
2012 
2013 bool ARMTTIImpl::useReductionIntrinsic(unsigned Opcode, Type *Ty,
2014                                        TTI::ReductionFlags Flags) const {
2015   return ST->hasMVEIntegerOps();
2016 }
2017 
2018 bool ARMTTIImpl::preferInLoopReduction(unsigned Opcode, Type *Ty,
2019                                        TTI::ReductionFlags Flags) const {
2020   if (!ST->hasMVEIntegerOps())
2021     return false;
2022 
2023   unsigned ScalarBits = Ty->getScalarSizeInBits();
2024   switch (Opcode) {
2025   case Instruction::Add:
2026     return ScalarBits <= 32;
2027   default:
2028     return false;
2029   }
2030 }
2031 
2032 bool ARMTTIImpl::preferPredicatedReductionSelect(
2033     unsigned Opcode, Type *Ty, TTI::ReductionFlags Flags) const {
2034   if (!ST->hasMVEIntegerOps())
2035     return false;
2036   return true;
2037 }
2038