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