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/IntrinsicInst.h"
24 #include "llvm/IR/PatternMatch.h"
25 #include "llvm/IR/Type.h"
26 #include "llvm/MC/SubtargetFeature.h"
27 #include "llvm/Support/Casting.h"
28 #include "llvm/Support/MachineValueType.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include <algorithm>
31 #include <cassert>
32 #include <cstdint>
33 #include <utility>
34 
35 using namespace llvm;
36 
37 #define DEBUG_TYPE "armtti"
38 
39 static cl::opt<bool> EnableMaskedLoadStores(
40   "enable-arm-maskedldst", cl::Hidden, cl::init(true),
41   cl::desc("Enable the generation of masked loads and stores"));
42 
43 static cl::opt<bool> DisableLowOverheadLoops(
44   "disable-arm-loloops", cl::Hidden, cl::init(false),
45   cl::desc("Disable the generation of low-overhead loops"));
46 
47 extern cl::opt<bool> DisableTailPredication;
48 
49 extern cl::opt<bool> EnableMaskedGatherScatters;
50 
51 bool ARMTTIImpl::areInlineCompatible(const Function *Caller,
52                                      const Function *Callee) const {
53   const TargetMachine &TM = getTLI()->getTargetMachine();
54   const FeatureBitset &CallerBits =
55       TM.getSubtargetImpl(*Caller)->getFeatureBits();
56   const FeatureBitset &CalleeBits =
57       TM.getSubtargetImpl(*Callee)->getFeatureBits();
58 
59   // To inline a callee, all features not in the whitelist must match exactly.
60   bool MatchExact = (CallerBits & ~InlineFeatureWhitelist) ==
61                     (CalleeBits & ~InlineFeatureWhitelist);
62   // For features in the whitelist, the callee's features must be a subset of
63   // the callers'.
64   bool MatchSubset = ((CallerBits & CalleeBits) & InlineFeatureWhitelist) ==
65                      (CalleeBits & InlineFeatureWhitelist);
66   return MatchExact && MatchSubset;
67 }
68 
69 bool ARMTTIImpl::shouldFavorBackedgeIndex(const Loop *L) const {
70   if (L->getHeader()->getParent()->hasOptSize())
71     return false;
72   if (ST->hasMVEIntegerOps())
73     return false;
74   return ST->isMClass() && ST->isThumb2() && L->getNumBlocks() == 1;
75 }
76 
77 bool ARMTTIImpl::shouldFavorPostInc() const {
78   if (ST->hasMVEIntegerOps())
79     return true;
80   return false;
81 }
82 
83 int ARMTTIImpl::getIntImmCost(const APInt &Imm, Type *Ty,
84                               TTI::TargetCostKind CostKind) {
85   assert(Ty->isIntegerTy());
86 
87  unsigned Bits = Ty->getPrimitiveSizeInBits();
88  if (Bits == 0 || Imm.getActiveBits() >= 64)
89    return 4;
90 
91   int64_t SImmVal = Imm.getSExtValue();
92   uint64_t ZImmVal = Imm.getZExtValue();
93   if (!ST->isThumb()) {
94     if ((SImmVal >= 0 && SImmVal < 65536) ||
95         (ARM_AM::getSOImmVal(ZImmVal) != -1) ||
96         (ARM_AM::getSOImmVal(~ZImmVal) != -1))
97       return 1;
98     return ST->hasV6T2Ops() ? 2 : 3;
99   }
100   if (ST->isThumb2()) {
101     if ((SImmVal >= 0 && SImmVal < 65536) ||
102         (ARM_AM::getT2SOImmVal(ZImmVal) != -1) ||
103         (ARM_AM::getT2SOImmVal(~ZImmVal) != -1))
104       return 1;
105     return ST->hasV6T2Ops() ? 2 : 3;
106   }
107   // Thumb1, any i8 imm cost 1.
108   if (Bits == 8 || (SImmVal >= 0 && SImmVal < 256))
109     return 1;
110   if ((~SImmVal < 256) || ARM_AM::isThumbImmShiftedVal(ZImmVal))
111     return 2;
112   // Load from constantpool.
113   return 3;
114 }
115 
116 // Constants smaller than 256 fit in the immediate field of
117 // Thumb1 instructions so we return a zero cost and 1 otherwise.
118 int ARMTTIImpl::getIntImmCodeSizeCost(unsigned Opcode, unsigned Idx,
119                                       const APInt &Imm, Type *Ty) {
120   if (Imm.isNonNegative() && Imm.getLimitedValue() < 256)
121     return 0;
122 
123   return 1;
124 }
125 
126 int ARMTTIImpl::getIntImmCostInst(unsigned Opcode, unsigned Idx, const APInt &Imm,
127                                   Type *Ty, TTI::TargetCostKind CostKind) {
128   // Division by a constant can be turned into multiplication, but only if we
129   // know it's constant. So it's not so much that the immediate is cheap (it's
130   // not), but that the alternative is worse.
131   // FIXME: this is probably unneeded with GlobalISel.
132   if ((Opcode == Instruction::SDiv || Opcode == Instruction::UDiv ||
133        Opcode == Instruction::SRem || Opcode == Instruction::URem) &&
134       Idx == 1)
135     return 0;
136 
137   if (Opcode == Instruction::And) {
138     // UXTB/UXTH
139     if (Imm == 255 || Imm == 65535)
140       return 0;
141     // Conversion to BIC is free, and means we can use ~Imm instead.
142     return std::min(getIntImmCost(Imm, Ty, CostKind),
143                     getIntImmCost(~Imm, Ty, CostKind));
144   }
145 
146   if (Opcode == Instruction::Add)
147     // Conversion to SUB is free, and means we can use -Imm instead.
148     return std::min(getIntImmCost(Imm, Ty, CostKind),
149                     getIntImmCost(-Imm, Ty, CostKind));
150 
151   if (Opcode == Instruction::ICmp && Imm.isNegative() &&
152       Ty->getIntegerBitWidth() == 32) {
153     int64_t NegImm = -Imm.getSExtValue();
154     if (ST->isThumb2() && NegImm < 1<<12)
155       // icmp X, #-C -> cmn X, #C
156       return 0;
157     if (ST->isThumb() && NegImm < 1<<8)
158       // icmp X, #-C -> adds X, #C
159       return 0;
160   }
161 
162   // xor a, -1 can always be folded to MVN
163   if (Opcode == Instruction::Xor && Imm.isAllOnesValue())
164     return 0;
165 
166   return getIntImmCost(Imm, Ty, CostKind);
167 }
168 
169 int ARMTTIImpl::getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src,
170                                  TTI::TargetCostKind CostKind,
171                                  const Instruction *I) {
172   int ISD = TLI->InstructionOpcodeToISD(Opcode);
173   assert(ISD && "Invalid opcode");
174 
175   // Single to/from double precision conversions.
176   static const CostTblEntry NEONFltDblTbl[] = {
177     // Vector fptrunc/fpext conversions.
178     { ISD::FP_ROUND,   MVT::v2f64, 2 },
179     { ISD::FP_EXTEND,  MVT::v2f32, 2 },
180     { ISD::FP_EXTEND,  MVT::v4f32, 4 }
181   };
182 
183   if (Src->isVectorTy() && ST->hasNEON() && (ISD == ISD::FP_ROUND ||
184                                           ISD == ISD::FP_EXTEND)) {
185     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
186     if (const auto *Entry = CostTableLookup(NEONFltDblTbl, ISD, LT.second))
187       return LT.first * Entry->Cost;
188   }
189 
190   EVT SrcTy = TLI->getValueType(DL, Src);
191   EVT DstTy = TLI->getValueType(DL, Dst);
192 
193   if (!SrcTy.isSimple() || !DstTy.isSimple())
194     return BaseT::getCastInstrCost(Opcode, Dst, Src, CostKind, I);
195 
196   // The extend of a load is free
197   if (I && isa<LoadInst>(I->getOperand(0))) {
198     static const TypeConversionCostTblEntry LoadConversionTbl[] = {
199         {ISD::SIGN_EXTEND, MVT::i32, MVT::i16, 0},
200         {ISD::ZERO_EXTEND, MVT::i32, MVT::i16, 0},
201         {ISD::SIGN_EXTEND, MVT::i32, MVT::i8, 0},
202         {ISD::ZERO_EXTEND, MVT::i32, MVT::i8, 0},
203         {ISD::SIGN_EXTEND, MVT::i16, MVT::i8, 0},
204         {ISD::ZERO_EXTEND, MVT::i16, MVT::i8, 0},
205         {ISD::SIGN_EXTEND, MVT::i64, MVT::i32, 1},
206         {ISD::ZERO_EXTEND, MVT::i64, MVT::i32, 1},
207         {ISD::SIGN_EXTEND, MVT::i64, MVT::i16, 1},
208         {ISD::ZERO_EXTEND, MVT::i64, MVT::i16, 1},
209         {ISD::SIGN_EXTEND, MVT::i64, MVT::i8, 1},
210         {ISD::ZERO_EXTEND, MVT::i64, MVT::i8, 1},
211     };
212     if (const auto *Entry = ConvertCostTableLookup(
213             LoadConversionTbl, ISD, DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
214       return Entry->Cost;
215 
216     static const TypeConversionCostTblEntry MVELoadConversionTbl[] = {
217         {ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 0},
218         {ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 0},
219         {ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 0},
220         {ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 0},
221         {ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 0},
222         {ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 0},
223     };
224     if (SrcTy.isVector() && ST->hasMVEIntegerOps()) {
225       if (const auto *Entry =
226               ConvertCostTableLookup(MVELoadConversionTbl, ISD,
227                                      DstTy.getSimpleVT(), SrcTy.getSimpleVT()))
228         return Entry->Cost;
229     }
230   }
231 
232   // NEON vector operations that can extend their inputs.
233   if ((ISD == ISD::SIGN_EXTEND || ISD == ISD::ZERO_EXTEND) &&
234       I && I->hasOneUse() && ST->hasNEON() && SrcTy.isVector()) {
235     static const TypeConversionCostTblEntry NEONDoubleWidthTbl[] = {
236       // vaddl
237       { ISD::ADD, MVT::v4i32, MVT::v4i16, 0 },
238       { ISD::ADD, MVT::v8i16, MVT::v8i8,  0 },
239       // vsubl
240       { ISD::SUB, MVT::v4i32, MVT::v4i16, 0 },
241       { ISD::SUB, MVT::v8i16, MVT::v8i8,  0 },
242       // vmull
243       { ISD::MUL, MVT::v4i32, MVT::v4i16, 0 },
244       { ISD::MUL, MVT::v8i16, MVT::v8i8,  0 },
245       // vshll
246       { ISD::SHL, MVT::v4i32, MVT::v4i16, 0 },
247       { ISD::SHL, MVT::v8i16, MVT::v8i8,  0 },
248     };
249 
250     auto *User = cast<Instruction>(*I->user_begin());
251     int UserISD = TLI->InstructionOpcodeToISD(User->getOpcode());
252     if (auto *Entry = ConvertCostTableLookup(NEONDoubleWidthTbl, UserISD,
253                                              DstTy.getSimpleVT(),
254                                              SrcTy.getSimpleVT())) {
255       return Entry->Cost;
256     }
257   }
258 
259   // Some arithmetic, load and store operations have specific instructions
260   // to cast up/down their types automatically at no extra cost.
261   // TODO: Get these tables to know at least what the related operations are.
262   static const TypeConversionCostTblEntry NEONVectorConversionTbl[] = {
263     { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
264     { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
265     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i32, 1 },
266     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i32, 1 },
267     { ISD::TRUNCATE,    MVT::v4i32, MVT::v4i64, 0 },
268     { ISD::TRUNCATE,    MVT::v4i16, MVT::v4i32, 1 },
269 
270     // The number of vmovl instructions for the extension.
271     { ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8,  1 },
272     { ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8,  1 },
273     { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8,  2 },
274     { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8,  2 },
275     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i8,  3 },
276     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i8,  3 },
277     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i16, 2 },
278     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i16, 2 },
279     { ISD::SIGN_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
280     { ISD::ZERO_EXTEND, MVT::v4i64, MVT::v4i16, 3 },
281     { ISD::SIGN_EXTEND, MVT::v8i32, MVT::v8i8, 3 },
282     { ISD::ZERO_EXTEND, MVT::v8i32, MVT::v8i8, 3 },
283     { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i8, 7 },
284     { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i8, 7 },
285     { ISD::SIGN_EXTEND, MVT::v8i64, MVT::v8i16, 6 },
286     { ISD::ZERO_EXTEND, MVT::v8i64, MVT::v8i16, 6 },
287     { ISD::SIGN_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
288     { ISD::ZERO_EXTEND, MVT::v16i32, MVT::v16i8, 6 },
289 
290     // Operations that we legalize using splitting.
291     { ISD::TRUNCATE,    MVT::v16i8, MVT::v16i32, 6 },
292     { ISD::TRUNCATE,    MVT::v8i8, MVT::v8i32, 3 },
293 
294     // Vector float <-> i32 conversions.
295     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i32, 1 },
296     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i32, 1 },
297 
298     { ISD::SINT_TO_FP,  MVT::v2f32, MVT::v2i8, 3 },
299     { ISD::UINT_TO_FP,  MVT::v2f32, MVT::v2i8, 3 },
300     { ISD::SINT_TO_FP,  MVT::v2f32, MVT::v2i16, 2 },
301     { ISD::UINT_TO_FP,  MVT::v2f32, MVT::v2i16, 2 },
302     { ISD::SINT_TO_FP,  MVT::v2f32, MVT::v2i32, 1 },
303     { ISD::UINT_TO_FP,  MVT::v2f32, MVT::v2i32, 1 },
304     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i1, 3 },
305     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i1, 3 },
306     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i8, 3 },
307     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i8, 3 },
308     { ISD::SINT_TO_FP,  MVT::v4f32, MVT::v4i16, 2 },
309     { ISD::UINT_TO_FP,  MVT::v4f32, MVT::v4i16, 2 },
310     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i16, 4 },
311     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i16, 4 },
312     { ISD::SINT_TO_FP,  MVT::v8f32, MVT::v8i32, 2 },
313     { ISD::UINT_TO_FP,  MVT::v8f32, MVT::v8i32, 2 },
314     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i16, 8 },
315     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i16, 8 },
316     { ISD::SINT_TO_FP,  MVT::v16f32, MVT::v16i32, 4 },
317     { ISD::UINT_TO_FP,  MVT::v16f32, MVT::v16i32, 4 },
318 
319     { ISD::FP_TO_SINT,  MVT::v4i32, MVT::v4f32, 1 },
320     { ISD::FP_TO_UINT,  MVT::v4i32, MVT::v4f32, 1 },
321     { ISD::FP_TO_SINT,  MVT::v4i8, MVT::v4f32, 3 },
322     { ISD::FP_TO_UINT,  MVT::v4i8, MVT::v4f32, 3 },
323     { ISD::FP_TO_SINT,  MVT::v4i16, MVT::v4f32, 2 },
324     { ISD::FP_TO_UINT,  MVT::v4i16, MVT::v4f32, 2 },
325 
326     // Vector double <-> i32 conversions.
327     { ISD::SINT_TO_FP,  MVT::v2f64, MVT::v2i32, 2 },
328     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i32, 2 },
329 
330     { ISD::SINT_TO_FP,  MVT::v2f64, MVT::v2i8, 4 },
331     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i8, 4 },
332     { ISD::SINT_TO_FP,  MVT::v2f64, MVT::v2i16, 3 },
333     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i16, 3 },
334     { ISD::SINT_TO_FP,  MVT::v2f64, MVT::v2i32, 2 },
335     { ISD::UINT_TO_FP,  MVT::v2f64, MVT::v2i32, 2 },
336 
337     { ISD::FP_TO_SINT,  MVT::v2i32, MVT::v2f64, 2 },
338     { ISD::FP_TO_UINT,  MVT::v2i32, MVT::v2f64, 2 },
339     { ISD::FP_TO_SINT,  MVT::v8i16, MVT::v8f32, 4 },
340     { ISD::FP_TO_UINT,  MVT::v8i16, MVT::v8f32, 4 },
341     { ISD::FP_TO_SINT,  MVT::v16i16, MVT::v16f32, 8 },
342     { ISD::FP_TO_UINT,  MVT::v16i16, MVT::v16f32, 8 }
343   };
344 
345   if (SrcTy.isVector() && ST->hasNEON()) {
346     if (const auto *Entry = ConvertCostTableLookup(NEONVectorConversionTbl, ISD,
347                                                    DstTy.getSimpleVT(),
348                                                    SrcTy.getSimpleVT()))
349       return Entry->Cost;
350   }
351 
352   // Scalar float to integer conversions.
353   static const TypeConversionCostTblEntry NEONFloatConversionTbl[] = {
354     { ISD::FP_TO_SINT,  MVT::i1, MVT::f32, 2 },
355     { ISD::FP_TO_UINT,  MVT::i1, MVT::f32, 2 },
356     { ISD::FP_TO_SINT,  MVT::i1, MVT::f64, 2 },
357     { ISD::FP_TO_UINT,  MVT::i1, MVT::f64, 2 },
358     { ISD::FP_TO_SINT,  MVT::i8, MVT::f32, 2 },
359     { ISD::FP_TO_UINT,  MVT::i8, MVT::f32, 2 },
360     { ISD::FP_TO_SINT,  MVT::i8, MVT::f64, 2 },
361     { ISD::FP_TO_UINT,  MVT::i8, MVT::f64, 2 },
362     { ISD::FP_TO_SINT,  MVT::i16, MVT::f32, 2 },
363     { ISD::FP_TO_UINT,  MVT::i16, MVT::f32, 2 },
364     { ISD::FP_TO_SINT,  MVT::i16, MVT::f64, 2 },
365     { ISD::FP_TO_UINT,  MVT::i16, MVT::f64, 2 },
366     { ISD::FP_TO_SINT,  MVT::i32, MVT::f32, 2 },
367     { ISD::FP_TO_UINT,  MVT::i32, MVT::f32, 2 },
368     { ISD::FP_TO_SINT,  MVT::i32, MVT::f64, 2 },
369     { ISD::FP_TO_UINT,  MVT::i32, MVT::f64, 2 },
370     { ISD::FP_TO_SINT,  MVT::i64, MVT::f32, 10 },
371     { ISD::FP_TO_UINT,  MVT::i64, MVT::f32, 10 },
372     { ISD::FP_TO_SINT,  MVT::i64, MVT::f64, 10 },
373     { ISD::FP_TO_UINT,  MVT::i64, MVT::f64, 10 }
374   };
375   if (SrcTy.isFloatingPoint() && ST->hasNEON()) {
376     if (const auto *Entry = ConvertCostTableLookup(NEONFloatConversionTbl, ISD,
377                                                    DstTy.getSimpleVT(),
378                                                    SrcTy.getSimpleVT()))
379       return Entry->Cost;
380   }
381 
382   // Scalar integer to float conversions.
383   static const TypeConversionCostTblEntry NEONIntegerConversionTbl[] = {
384     { ISD::SINT_TO_FP,  MVT::f32, MVT::i1, 2 },
385     { ISD::UINT_TO_FP,  MVT::f32, MVT::i1, 2 },
386     { ISD::SINT_TO_FP,  MVT::f64, MVT::i1, 2 },
387     { ISD::UINT_TO_FP,  MVT::f64, MVT::i1, 2 },
388     { ISD::SINT_TO_FP,  MVT::f32, MVT::i8, 2 },
389     { ISD::UINT_TO_FP,  MVT::f32, MVT::i8, 2 },
390     { ISD::SINT_TO_FP,  MVT::f64, MVT::i8, 2 },
391     { ISD::UINT_TO_FP,  MVT::f64, MVT::i8, 2 },
392     { ISD::SINT_TO_FP,  MVT::f32, MVT::i16, 2 },
393     { ISD::UINT_TO_FP,  MVT::f32, MVT::i16, 2 },
394     { ISD::SINT_TO_FP,  MVT::f64, MVT::i16, 2 },
395     { ISD::UINT_TO_FP,  MVT::f64, MVT::i16, 2 },
396     { ISD::SINT_TO_FP,  MVT::f32, MVT::i32, 2 },
397     { ISD::UINT_TO_FP,  MVT::f32, MVT::i32, 2 },
398     { ISD::SINT_TO_FP,  MVT::f64, MVT::i32, 2 },
399     { ISD::UINT_TO_FP,  MVT::f64, MVT::i32, 2 },
400     { ISD::SINT_TO_FP,  MVT::f32, MVT::i64, 10 },
401     { ISD::UINT_TO_FP,  MVT::f32, MVT::i64, 10 },
402     { ISD::SINT_TO_FP,  MVT::f64, MVT::i64, 10 },
403     { ISD::UINT_TO_FP,  MVT::f64, MVT::i64, 10 }
404   };
405 
406   if (SrcTy.isInteger() && ST->hasNEON()) {
407     if (const auto *Entry = ConvertCostTableLookup(NEONIntegerConversionTbl,
408                                                    ISD, DstTy.getSimpleVT(),
409                                                    SrcTy.getSimpleVT()))
410       return Entry->Cost;
411   }
412 
413   // MVE extend costs, taken from codegen tests. i8->i16 or i16->i32 is one
414   // instruction, i8->i32 is two. i64 zexts are an VAND with a constant, sext
415   // are linearised so take more.
416   static const TypeConversionCostTblEntry MVEVectorConversionTbl[] = {
417     { ISD::SIGN_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
418     { ISD::ZERO_EXTEND, MVT::v8i16, MVT::v8i8, 1 },
419     { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i8, 2 },
420     { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i8, 2 },
421     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i8, 10 },
422     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i8, 2 },
423     { ISD::SIGN_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
424     { ISD::ZERO_EXTEND, MVT::v4i32, MVT::v4i16, 1 },
425     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i16, 10 },
426     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i16, 2 },
427     { ISD::SIGN_EXTEND, MVT::v2i64, MVT::v2i32, 8 },
428     { ISD::ZERO_EXTEND, MVT::v2i64, MVT::v2i32, 2 },
429   };
430 
431   if (SrcTy.isVector() && ST->hasMVEIntegerOps()) {
432     if (const auto *Entry = ConvertCostTableLookup(MVEVectorConversionTbl,
433                                                    ISD, DstTy.getSimpleVT(),
434                                                    SrcTy.getSimpleVT()))
435       return Entry->Cost * ST->getMVEVectorCostFactor();
436   }
437 
438   // Scalar integer conversion costs.
439   static const TypeConversionCostTblEntry ARMIntegerConversionTbl[] = {
440     // i16 -> i64 requires two dependent operations.
441     { ISD::SIGN_EXTEND, MVT::i64, MVT::i16, 2 },
442 
443     // Truncates on i64 are assumed to be free.
444     { ISD::TRUNCATE,    MVT::i32, MVT::i64, 0 },
445     { ISD::TRUNCATE,    MVT::i16, MVT::i64, 0 },
446     { ISD::TRUNCATE,    MVT::i8,  MVT::i64, 0 },
447     { ISD::TRUNCATE,    MVT::i1,  MVT::i64, 0 }
448   };
449 
450   if (SrcTy.isInteger()) {
451     if (const auto *Entry = ConvertCostTableLookup(ARMIntegerConversionTbl, ISD,
452                                                    DstTy.getSimpleVT(),
453                                                    SrcTy.getSimpleVT()))
454       return Entry->Cost;
455   }
456 
457   int BaseCost = ST->hasMVEIntegerOps() && Src->isVectorTy()
458                      ? ST->getMVEVectorCostFactor()
459                      : 1;
460   return BaseCost * BaseT::getCastInstrCost(Opcode, Dst, Src, CostKind, I);
461 }
462 
463 int ARMTTIImpl::getVectorInstrCost(unsigned Opcode, Type *ValTy,
464                                    unsigned Index) {
465   // Penalize inserting into an D-subregister. We end up with a three times
466   // lower estimated throughput on swift.
467   if (ST->hasSlowLoadDSubregister() && Opcode == Instruction::InsertElement &&
468       ValTy->isVectorTy() && ValTy->getScalarSizeInBits() <= 32)
469     return 3;
470 
471   if (ST->hasNEON() && (Opcode == Instruction::InsertElement ||
472                         Opcode == Instruction::ExtractElement)) {
473     // Cross-class copies are expensive on many microarchitectures,
474     // so assume they are expensive by default.
475     if (cast<VectorType>(ValTy)->getElementType()->isIntegerTy())
476       return 3;
477 
478     // Even if it's not a cross class copy, this likely leads to mixing
479     // of NEON and VFP code and should be therefore penalized.
480     if (ValTy->isVectorTy() &&
481         ValTy->getScalarSizeInBits() <= 32)
482       return std::max(BaseT::getVectorInstrCost(Opcode, ValTy, Index), 2U);
483   }
484 
485   if (ST->hasMVEIntegerOps() && (Opcode == Instruction::InsertElement ||
486                                  Opcode == Instruction::ExtractElement)) {
487     // We say MVE moves costs at least the MVEVectorCostFactor, even though
488     // they are scalar instructions. This helps prevent mixing scalar and
489     // vector, to prevent vectorising where we end up just scalarising the
490     // result anyway.
491     return std::max(BaseT::getVectorInstrCost(Opcode, ValTy, Index),
492                     ST->getMVEVectorCostFactor()) *
493            cast<VectorType>(ValTy)->getNumElements() / 2;
494   }
495 
496   return BaseT::getVectorInstrCost(Opcode, ValTy, Index);
497 }
498 
499 int ARMTTIImpl::getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy,
500                                    TTI::TargetCostKind CostKind,
501                                    const Instruction *I) {
502   int ISD = TLI->InstructionOpcodeToISD(Opcode);
503   // On NEON a vector select gets lowered to vbsl.
504   if (ST->hasNEON() && ValTy->isVectorTy() && ISD == ISD::SELECT) {
505     // Lowering of some vector selects is currently far from perfect.
506     static const TypeConversionCostTblEntry NEONVectorSelectTbl[] = {
507       { ISD::SELECT, MVT::v4i1, MVT::v4i64, 4*4 + 1*2 + 1 },
508       { ISD::SELECT, MVT::v8i1, MVT::v8i64, 50 },
509       { ISD::SELECT, MVT::v16i1, MVT::v16i64, 100 }
510     };
511 
512     EVT SelCondTy = TLI->getValueType(DL, CondTy);
513     EVT SelValTy = TLI->getValueType(DL, ValTy);
514     if (SelCondTy.isSimple() && SelValTy.isSimple()) {
515       if (const auto *Entry = ConvertCostTableLookup(NEONVectorSelectTbl, ISD,
516                                                      SelCondTy.getSimpleVT(),
517                                                      SelValTy.getSimpleVT()))
518         return Entry->Cost;
519     }
520 
521     std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, ValTy);
522     return LT.first;
523   }
524 
525   int BaseCost = ST->hasMVEIntegerOps() && ValTy->isVectorTy()
526                      ? ST->getMVEVectorCostFactor()
527                      : 1;
528   return BaseCost * BaseT::getCmpSelInstrCost(Opcode, ValTy, CondTy, CostKind,
529                                               I);
530 }
531 
532 int ARMTTIImpl::getAddressComputationCost(Type *Ty, ScalarEvolution *SE,
533                                           const SCEV *Ptr) {
534   // Address computations in vectorized code with non-consecutive addresses will
535   // likely result in more instructions compared to scalar code where the
536   // computation can more often be merged into the index mode. The resulting
537   // extra micro-ops can significantly decrease throughput.
538   unsigned NumVectorInstToHideOverhead = 10;
539   int MaxMergeDistance = 64;
540 
541   if (ST->hasNEON()) {
542     if (Ty->isVectorTy() && SE &&
543         !BaseT::isConstantStridedAccessLessThan(SE, Ptr, MaxMergeDistance + 1))
544       return NumVectorInstToHideOverhead;
545 
546     // In many cases the address computation is not merged into the instruction
547     // addressing mode.
548     return 1;
549   }
550   return BaseT::getAddressComputationCost(Ty, SE, Ptr);
551 }
552 
553 bool ARMTTIImpl::isLegalMaskedLoad(Type *DataTy, MaybeAlign Alignment) {
554   if (!EnableMaskedLoadStores || !ST->hasMVEIntegerOps())
555     return false;
556 
557   if (auto *VecTy = dyn_cast<VectorType>(DataTy)) {
558     // Don't support v2i1 yet.
559     if (VecTy->getNumElements() == 2)
560       return false;
561 
562     // We don't support extending fp types.
563      unsigned VecWidth = DataTy->getPrimitiveSizeInBits();
564     if (VecWidth != 128 && VecTy->getElementType()->isFloatingPointTy())
565       return false;
566   }
567 
568   unsigned EltWidth = DataTy->getScalarSizeInBits();
569   return (EltWidth == 32 && (!Alignment || Alignment >= 4)) ||
570          (EltWidth == 16 && (!Alignment || Alignment >= 2)) ||
571          (EltWidth == 8);
572 }
573 
574 bool ARMTTIImpl::isLegalMaskedGather(Type *Ty, MaybeAlign Alignment) {
575   if (!EnableMaskedGatherScatters || !ST->hasMVEIntegerOps())
576     return false;
577 
578   // This method is called in 2 places:
579   //  - from the vectorizer with a scalar type, in which case we need to get
580   //  this as good as we can with the limited info we have (and rely on the cost
581   //  model for the rest).
582   //  - from the masked intrinsic lowering pass with the actual vector type.
583   // For MVE, we have a custom lowering pass that will already have custom
584   // legalised any gathers that we can to MVE intrinsics, and want to expand all
585   // the rest. The pass runs before the masked intrinsic lowering pass, so if we
586   // are here, we know we want to expand.
587   if (isa<VectorType>(Ty))
588     return false;
589 
590   unsigned EltWidth = Ty->getScalarSizeInBits();
591   return ((EltWidth == 32 && (!Alignment || Alignment >= 4)) ||
592           (EltWidth == 16 && (!Alignment || Alignment >= 2)) || EltWidth == 8);
593 }
594 
595 int ARMTTIImpl::getMemcpyCost(const Instruction *I) {
596   const MemCpyInst *MI = dyn_cast<MemCpyInst>(I);
597   assert(MI && "MemcpyInst expected");
598   ConstantInt *C = dyn_cast<ConstantInt>(MI->getLength());
599 
600   // To model the cost of a library call, we assume 1 for the call, and
601   // 3 for the argument setup.
602   const unsigned LibCallCost = 4;
603 
604   // If 'size' is not a constant, a library call will be generated.
605   if (!C)
606     return LibCallCost;
607 
608   const unsigned Size = C->getValue().getZExtValue();
609   const Align DstAlign = *MI->getDestAlign();
610   const Align SrcAlign = *MI->getSourceAlign();
611   const Function *F = I->getParent()->getParent();
612   const unsigned Limit = TLI->getMaxStoresPerMemmove(F->hasMinSize());
613   std::vector<EVT> MemOps;
614 
615   // MemOps will be poplulated with a list of data types that needs to be
616   // loaded and stored. That's why we multiply the number of elements by 2 to
617   // get the cost for this memcpy.
618   if (getTLI()->findOptimalMemOpLowering(
619           MemOps, Limit,
620           MemOp::Copy(Size, /*DstAlignCanChange*/ false, DstAlign, SrcAlign,
621                       /*IsVolatile*/ true),
622           MI->getDestAddressSpace(), MI->getSourceAddressSpace(),
623           F->getAttributes()))
624     return MemOps.size() * 2;
625 
626   // If we can't find an optimal memop lowering, return the default cost
627   return LibCallCost;
628 }
629 
630 int ARMTTIImpl::getShuffleCost(TTI::ShuffleKind Kind, VectorType *Tp,
631                                int Index, VectorType *SubTp) {
632   if (ST->hasNEON()) {
633     if (Kind == TTI::SK_Broadcast) {
634       static const CostTblEntry NEONDupTbl[] = {
635           // VDUP handles these cases.
636           {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
637           {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
638           {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
639           {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
640           {ISD::VECTOR_SHUFFLE, MVT::v4i16, 1},
641           {ISD::VECTOR_SHUFFLE, MVT::v8i8, 1},
642 
643           {ISD::VECTOR_SHUFFLE, MVT::v4i32, 1},
644           {ISD::VECTOR_SHUFFLE, MVT::v4f32, 1},
645           {ISD::VECTOR_SHUFFLE, MVT::v8i16, 1},
646           {ISD::VECTOR_SHUFFLE, MVT::v16i8, 1}};
647 
648       std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
649 
650       if (const auto *Entry =
651               CostTableLookup(NEONDupTbl, ISD::VECTOR_SHUFFLE, LT.second))
652         return LT.first * Entry->Cost;
653     }
654     if (Kind == TTI::SK_Reverse) {
655       static const CostTblEntry NEONShuffleTbl[] = {
656           // Reverse shuffle cost one instruction if we are shuffling within a
657           // double word (vrev) or two if we shuffle a quad word (vrev, vext).
658           {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
659           {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
660           {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
661           {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
662           {ISD::VECTOR_SHUFFLE, MVT::v4i16, 1},
663           {ISD::VECTOR_SHUFFLE, MVT::v8i8, 1},
664 
665           {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2},
666           {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2},
667           {ISD::VECTOR_SHUFFLE, MVT::v8i16, 2},
668           {ISD::VECTOR_SHUFFLE, MVT::v16i8, 2}};
669 
670       std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
671 
672       if (const auto *Entry =
673               CostTableLookup(NEONShuffleTbl, ISD::VECTOR_SHUFFLE, LT.second))
674         return LT.first * Entry->Cost;
675     }
676     if (Kind == TTI::SK_Select) {
677       static const CostTblEntry NEONSelShuffleTbl[] = {
678           // Select shuffle cost table for ARM. Cost is the number of
679           // instructions
680           // required to create the shuffled vector.
681 
682           {ISD::VECTOR_SHUFFLE, MVT::v2f32, 1},
683           {ISD::VECTOR_SHUFFLE, MVT::v2i64, 1},
684           {ISD::VECTOR_SHUFFLE, MVT::v2f64, 1},
685           {ISD::VECTOR_SHUFFLE, MVT::v2i32, 1},
686 
687           {ISD::VECTOR_SHUFFLE, MVT::v4i32, 2},
688           {ISD::VECTOR_SHUFFLE, MVT::v4f32, 2},
689           {ISD::VECTOR_SHUFFLE, MVT::v4i16, 2},
690 
691           {ISD::VECTOR_SHUFFLE, MVT::v8i16, 16},
692 
693           {ISD::VECTOR_SHUFFLE, MVT::v16i8, 32}};
694 
695       std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
696       if (const auto *Entry = CostTableLookup(NEONSelShuffleTbl,
697                                               ISD::VECTOR_SHUFFLE, LT.second))
698         return LT.first * Entry->Cost;
699     }
700   }
701   if (ST->hasMVEIntegerOps()) {
702     if (Kind == TTI::SK_Broadcast) {
703       static const CostTblEntry MVEDupTbl[] = {
704           // VDUP handles these cases.
705           {ISD::VECTOR_SHUFFLE, MVT::v4i32, 1},
706           {ISD::VECTOR_SHUFFLE, MVT::v8i16, 1},
707           {ISD::VECTOR_SHUFFLE, MVT::v16i8, 1},
708           {ISD::VECTOR_SHUFFLE, MVT::v4f32, 1},
709           {ISD::VECTOR_SHUFFLE, MVT::v8f16, 1}};
710 
711       std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Tp);
712 
713       if (const auto *Entry = CostTableLookup(MVEDupTbl, ISD::VECTOR_SHUFFLE,
714                                               LT.second))
715         return LT.first * Entry->Cost * ST->getMVEVectorCostFactor();
716     }
717   }
718   int BaseCost = ST->hasMVEIntegerOps() && Tp->isVectorTy()
719                      ? ST->getMVEVectorCostFactor()
720                      : 1;
721   return BaseCost * BaseT::getShuffleCost(Kind, Tp, Index, SubTp);
722 }
723 
724 int ARMTTIImpl::getArithmeticInstrCost(unsigned Opcode, Type *Ty,
725                                        TTI::TargetCostKind CostKind,
726                                        TTI::OperandValueKind Op1Info,
727                                        TTI::OperandValueKind Op2Info,
728                                        TTI::OperandValueProperties Opd1PropInfo,
729                                        TTI::OperandValueProperties Opd2PropInfo,
730                                        ArrayRef<const Value *> Args,
731                                        const Instruction *CxtI) {
732   int ISDOpcode = TLI->InstructionOpcodeToISD(Opcode);
733   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Ty);
734 
735   if (ST->hasNEON()) {
736     const unsigned FunctionCallDivCost = 20;
737     const unsigned ReciprocalDivCost = 10;
738     static const CostTblEntry CostTbl[] = {
739       // Division.
740       // These costs are somewhat random. Choose a cost of 20 to indicate that
741       // vectorizing devision (added function call) is going to be very expensive.
742       // Double registers types.
743       { ISD::SDIV, MVT::v1i64, 1 * FunctionCallDivCost},
744       { ISD::UDIV, MVT::v1i64, 1 * FunctionCallDivCost},
745       { ISD::SREM, MVT::v1i64, 1 * FunctionCallDivCost},
746       { ISD::UREM, MVT::v1i64, 1 * FunctionCallDivCost},
747       { ISD::SDIV, MVT::v2i32, 2 * FunctionCallDivCost},
748       { ISD::UDIV, MVT::v2i32, 2 * FunctionCallDivCost},
749       { ISD::SREM, MVT::v2i32, 2 * FunctionCallDivCost},
750       { ISD::UREM, MVT::v2i32, 2 * FunctionCallDivCost},
751       { ISD::SDIV, MVT::v4i16,     ReciprocalDivCost},
752       { ISD::UDIV, MVT::v4i16,     ReciprocalDivCost},
753       { ISD::SREM, MVT::v4i16, 4 * FunctionCallDivCost},
754       { ISD::UREM, MVT::v4i16, 4 * FunctionCallDivCost},
755       { ISD::SDIV, MVT::v8i8,      ReciprocalDivCost},
756       { ISD::UDIV, MVT::v8i8,      ReciprocalDivCost},
757       { ISD::SREM, MVT::v8i8,  8 * FunctionCallDivCost},
758       { ISD::UREM, MVT::v8i8,  8 * FunctionCallDivCost},
759       // Quad register types.
760       { ISD::SDIV, MVT::v2i64, 2 * FunctionCallDivCost},
761       { ISD::UDIV, MVT::v2i64, 2 * FunctionCallDivCost},
762       { ISD::SREM, MVT::v2i64, 2 * FunctionCallDivCost},
763       { ISD::UREM, MVT::v2i64, 2 * FunctionCallDivCost},
764       { ISD::SDIV, MVT::v4i32, 4 * FunctionCallDivCost},
765       { ISD::UDIV, MVT::v4i32, 4 * FunctionCallDivCost},
766       { ISD::SREM, MVT::v4i32, 4 * FunctionCallDivCost},
767       { ISD::UREM, MVT::v4i32, 4 * FunctionCallDivCost},
768       { ISD::SDIV, MVT::v8i16, 8 * FunctionCallDivCost},
769       { ISD::UDIV, MVT::v8i16, 8 * FunctionCallDivCost},
770       { ISD::SREM, MVT::v8i16, 8 * FunctionCallDivCost},
771       { ISD::UREM, MVT::v8i16, 8 * FunctionCallDivCost},
772       { ISD::SDIV, MVT::v16i8, 16 * FunctionCallDivCost},
773       { ISD::UDIV, MVT::v16i8, 16 * FunctionCallDivCost},
774       { ISD::SREM, MVT::v16i8, 16 * FunctionCallDivCost},
775       { ISD::UREM, MVT::v16i8, 16 * FunctionCallDivCost},
776       // Multiplication.
777     };
778 
779     if (const auto *Entry = CostTableLookup(CostTbl, ISDOpcode, LT.second))
780       return LT.first * Entry->Cost;
781 
782     int Cost = BaseT::getArithmeticInstrCost(Opcode, Ty, CostKind, Op1Info,
783                                              Op2Info,
784                                              Opd1PropInfo, Opd2PropInfo);
785 
786     // This is somewhat of a hack. The problem that we are facing is that SROA
787     // creates a sequence of shift, and, or instructions to construct values.
788     // These sequences are recognized by the ISel and have zero-cost. Not so for
789     // the vectorized code. Because we have support for v2i64 but not i64 those
790     // sequences look particularly beneficial to vectorize.
791     // To work around this we increase the cost of v2i64 operations to make them
792     // seem less beneficial.
793     if (LT.second == MVT::v2i64 &&
794         Op2Info == TargetTransformInfo::OK_UniformConstantValue)
795       Cost += 4;
796 
797     return Cost;
798   }
799 
800   // If this operation is a shift on arm/thumb2, it might well be folded into
801   // the following instruction, hence having a cost of 0.
802   auto LooksLikeAFreeShift = [&]() {
803     if (ST->isThumb1Only() || Ty->isVectorTy())
804       return false;
805 
806     if (!CxtI || !CxtI->hasOneUse() || !CxtI->isShift())
807       return false;
808     if (Op2Info != TargetTransformInfo::OK_UniformConstantValue)
809       return false;
810 
811     // Folded into a ADC/ADD/AND/BIC/CMP/EOR/MVN/ORR/ORN/RSB/SBC/SUB
812     switch (cast<Instruction>(CxtI->user_back())->getOpcode()) {
813     case Instruction::Add:
814     case Instruction::Sub:
815     case Instruction::And:
816     case Instruction::Xor:
817     case Instruction::Or:
818     case Instruction::ICmp:
819       return true;
820     default:
821       return false;
822     }
823   };
824   if (LooksLikeAFreeShift())
825     return 0;
826 
827   int BaseCost = ST->hasMVEIntegerOps() && Ty->isVectorTy()
828                      ? ST->getMVEVectorCostFactor()
829                      : 1;
830 
831   // The rest of this mostly follows what is done in BaseT::getArithmeticInstrCost,
832   // without treating floats as more expensive that scalars or increasing the
833   // costs for custom operations. The results is also multiplied by the
834   // MVEVectorCostFactor where appropriate.
835   if (TLI->isOperationLegalOrCustomOrPromote(ISDOpcode, LT.second))
836     return LT.first * BaseCost;
837 
838   // Else this is expand, assume that we need to scalarize this op.
839   if (auto *VTy = dyn_cast<VectorType>(Ty)) {
840     unsigned Num = VTy->getNumElements();
841     unsigned Cost = getArithmeticInstrCost(Opcode, Ty->getScalarType(),
842                                            CostKind);
843     // Return the cost of multiple scalar invocation plus the cost of
844     // inserting and extracting the values.
845     return BaseT::getScalarizationOverhead(VTy, Args) + Num * Cost;
846   }
847 
848   return BaseCost;
849 }
850 
851 int ARMTTIImpl::getMemoryOpCost(unsigned Opcode, Type *Src,
852                                 MaybeAlign Alignment, unsigned AddressSpace,
853                                 TTI::TargetCostKind CostKind,
854                                 const Instruction *I) {
855   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, Src);
856 
857   if (ST->hasNEON() && Src->isVectorTy() &&
858       (Alignment && *Alignment != Align(16)) &&
859       cast<VectorType>(Src)->getElementType()->isDoubleTy()) {
860     // Unaligned loads/stores are extremely inefficient.
861     // We need 4 uops for vst.1/vld.1 vs 1uop for vldr/vstr.
862     return LT.first * 4;
863   }
864   int BaseCost = ST->hasMVEIntegerOps() && Src->isVectorTy()
865                      ? ST->getMVEVectorCostFactor()
866                      : 1;
867   return BaseCost * LT.first;
868 }
869 
870 int ARMTTIImpl::getInterleavedMemoryOpCost(
871     unsigned Opcode, Type *VecTy, unsigned Factor, ArrayRef<unsigned> Indices,
872     unsigned Alignment, unsigned AddressSpace,
873     TTI::TargetCostKind CostKind,
874     bool UseMaskForCond, bool UseMaskForGaps) {
875   assert(Factor >= 2 && "Invalid interleave factor");
876   assert(isa<VectorType>(VecTy) && "Expect a vector type");
877 
878   // vldN/vstN doesn't support vector types of i64/f64 element.
879   bool EltIs64Bits = DL.getTypeSizeInBits(VecTy->getScalarType()) == 64;
880 
881   if (Factor <= TLI->getMaxSupportedInterleaveFactor() && !EltIs64Bits &&
882       !UseMaskForCond && !UseMaskForGaps) {
883     unsigned NumElts = cast<VectorType>(VecTy)->getNumElements();
884     auto *SubVecTy = VectorType::get(VecTy->getScalarType(), NumElts / Factor);
885 
886     // vldN/vstN only support legal vector types of size 64 or 128 in bits.
887     // Accesses having vector types that are a multiple of 128 bits can be
888     // matched to more than one vldN/vstN instruction.
889     int BaseCost = ST->hasMVEIntegerOps() ? ST->getMVEVectorCostFactor() : 1;
890     if (NumElts % Factor == 0 &&
891         TLI->isLegalInterleavedAccessType(Factor, SubVecTy, DL))
892       return Factor * BaseCost * TLI->getNumInterleavedAccesses(SubVecTy, DL);
893 
894     // Some smaller than legal interleaved patterns are cheap as we can make
895     // use of the vmovn or vrev patterns to interleave a standard load. This is
896     // true for v4i8, v8i8 and v4i16 at least (but not for v4f16 as it is
897     // promoted differently). The cost of 2 here is then a load and vrev or
898     // vmovn.
899     if (ST->hasMVEIntegerOps() && Factor == 2 && NumElts / Factor > 2 &&
900         VecTy->isIntOrIntVectorTy() && DL.getTypeSizeInBits(SubVecTy) <= 64)
901       return 2 * BaseCost;
902   }
903 
904   return BaseT::getInterleavedMemoryOpCost(Opcode, VecTy, Factor, Indices,
905                                            Alignment, AddressSpace, CostKind,
906                                            UseMaskForCond, UseMaskForGaps);
907 }
908 
909 unsigned ARMTTIImpl::getGatherScatterOpCost(unsigned Opcode, Type *DataTy,
910                                             Value *Ptr, bool VariableMask,
911                                             unsigned Alignment,
912                                             TTI::TargetCostKind CostKind,
913                                             const Instruction *I) {
914   using namespace PatternMatch;
915   if (!ST->hasMVEIntegerOps() || !EnableMaskedGatherScatters)
916     return BaseT::getGatherScatterOpCost(Opcode, DataTy, Ptr, VariableMask,
917                                          Alignment, CostKind, I);
918 
919   assert(DataTy->isVectorTy() && "Can't do gather/scatters on scalar!");
920   VectorType *VTy = cast<VectorType>(DataTy);
921 
922   // TODO: Splitting, once we do that.
923 
924   unsigned NumElems = VTy->getNumElements();
925   unsigned EltSize = VTy->getScalarSizeInBits();
926   std::pair<int, MVT> LT = TLI->getTypeLegalizationCost(DL, DataTy);
927 
928   // For now, it is assumed that for the MVE gather instructions the loads are
929   // all effectively serialised. This means the cost is the scalar cost
930   // multiplied by the number of elements being loaded. This is possibly very
931   // conservative, but even so we still end up vectorising loops because the
932   // cost per iteration for many loops is lower than for scalar loops.
933   unsigned VectorCost = NumElems * LT.first;
934   // The scalarization cost should be a lot higher. We use the number of vector
935   // elements plus the scalarization overhead.
936   unsigned ScalarCost =
937       NumElems * LT.first + BaseT::getScalarizationOverhead(VTy, {});
938 
939   if (Alignment < EltSize / 8)
940     return ScalarCost;
941 
942   unsigned ExtSize = EltSize;
943   // Check whether there's a single user that asks for an extended type
944   if (I != nullptr) {
945     // Dependent of the caller of this function, a gather instruction will
946     // either have opcode Instruction::Load or be a call to the masked_gather
947     // intrinsic
948     if ((I->getOpcode() == Instruction::Load ||
949          match(I, m_Intrinsic<Intrinsic::masked_gather>())) &&
950         I->hasOneUse()) {
951       const User *Us = *I->users().begin();
952       if (isa<ZExtInst>(Us) || isa<SExtInst>(Us)) {
953         // only allow valid type combinations
954         unsigned TypeSize =
955             cast<Instruction>(Us)->getType()->getScalarSizeInBits();
956         if (((TypeSize == 32 && (EltSize == 8 || EltSize == 16)) ||
957              (TypeSize == 16 && EltSize == 8)) &&
958             TypeSize * NumElems == 128) {
959           ExtSize = TypeSize;
960         }
961       }
962     }
963     // Check whether the input data needs to be truncated
964     TruncInst *T;
965     if ((I->getOpcode() == Instruction::Store ||
966          match(I, m_Intrinsic<Intrinsic::masked_scatter>())) &&
967         (T = dyn_cast<TruncInst>(I->getOperand(0)))) {
968       // Only allow valid type combinations
969       unsigned TypeSize = T->getOperand(0)->getType()->getScalarSizeInBits();
970       if (((EltSize == 16 && TypeSize == 32) ||
971            (EltSize == 8 && (TypeSize == 32 || TypeSize == 16))) &&
972           TypeSize * NumElems == 128)
973         ExtSize = TypeSize;
974     }
975   }
976 
977   if (ExtSize * NumElems != 128 || NumElems < 4)
978     return ScalarCost;
979 
980   // Any (aligned) i32 gather will not need to be scalarised.
981   if (ExtSize == 32)
982     return VectorCost;
983   // For smaller types, we need to ensure that the gep's inputs are correctly
984   // extended from a small enough value. Other sizes (including i64) are
985   // scalarized for now.
986   if (ExtSize != 8 && ExtSize != 16)
987     return ScalarCost;
988 
989   if (auto BC = dyn_cast<BitCastInst>(Ptr))
990     Ptr = BC->getOperand(0);
991   if (auto *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
992     if (GEP->getNumOperands() != 2)
993       return ScalarCost;
994     unsigned Scale = DL.getTypeAllocSize(GEP->getResultElementType());
995     // Scale needs to be correct (which is only relevant for i16s).
996     if (Scale != 1 && Scale * 8 != ExtSize)
997       return ScalarCost;
998     // And we need to zext (not sext) the indexes from a small enough type.
999     if (auto ZExt = dyn_cast<ZExtInst>(GEP->getOperand(1))) {
1000       if (ZExt->getOperand(0)->getType()->getScalarSizeInBits() <= ExtSize)
1001         return VectorCost;
1002     }
1003     return ScalarCost;
1004   }
1005   return ScalarCost;
1006 }
1007 
1008 bool ARMTTIImpl::isLoweredToCall(const Function *F) {
1009   if (!F->isIntrinsic())
1010     BaseT::isLoweredToCall(F);
1011 
1012   // Assume all Arm-specific intrinsics map to an instruction.
1013   if (F->getName().startswith("llvm.arm"))
1014     return false;
1015 
1016   switch (F->getIntrinsicID()) {
1017   default: break;
1018   case Intrinsic::powi:
1019   case Intrinsic::sin:
1020   case Intrinsic::cos:
1021   case Intrinsic::pow:
1022   case Intrinsic::log:
1023   case Intrinsic::log10:
1024   case Intrinsic::log2:
1025   case Intrinsic::exp:
1026   case Intrinsic::exp2:
1027     return true;
1028   case Intrinsic::sqrt:
1029   case Intrinsic::fabs:
1030   case Intrinsic::copysign:
1031   case Intrinsic::floor:
1032   case Intrinsic::ceil:
1033   case Intrinsic::trunc:
1034   case Intrinsic::rint:
1035   case Intrinsic::nearbyint:
1036   case Intrinsic::round:
1037   case Intrinsic::canonicalize:
1038   case Intrinsic::lround:
1039   case Intrinsic::llround:
1040   case Intrinsic::lrint:
1041   case Intrinsic::llrint:
1042     if (F->getReturnType()->isDoubleTy() && !ST->hasFP64())
1043       return true;
1044     if (F->getReturnType()->isHalfTy() && !ST->hasFullFP16())
1045       return true;
1046     // Some operations can be handled by vector instructions and assume
1047     // unsupported vectors will be expanded into supported scalar ones.
1048     // TODO Handle scalar operations properly.
1049     return !ST->hasFPARMv8Base() && !ST->hasVFP2Base();
1050   case Intrinsic::masked_store:
1051   case Intrinsic::masked_load:
1052   case Intrinsic::masked_gather:
1053   case Intrinsic::masked_scatter:
1054     return !ST->hasMVEIntegerOps();
1055   case Intrinsic::sadd_with_overflow:
1056   case Intrinsic::uadd_with_overflow:
1057   case Intrinsic::ssub_with_overflow:
1058   case Intrinsic::usub_with_overflow:
1059   case Intrinsic::sadd_sat:
1060   case Intrinsic::uadd_sat:
1061   case Intrinsic::ssub_sat:
1062   case Intrinsic::usub_sat:
1063     return false;
1064   }
1065 
1066   return BaseT::isLoweredToCall(F);
1067 }
1068 
1069 bool ARMTTIImpl::isHardwareLoopProfitable(Loop *L, ScalarEvolution &SE,
1070                                           AssumptionCache &AC,
1071                                           TargetLibraryInfo *LibInfo,
1072                                           HardwareLoopInfo &HWLoopInfo) {
1073   // Low-overhead branches are only supported in the 'low-overhead branch'
1074   // extension of v8.1-m.
1075   if (!ST->hasLOB() || DisableLowOverheadLoops) {
1076     LLVM_DEBUG(dbgs() << "ARMHWLoops: Disabled\n");
1077     return false;
1078   }
1079 
1080   if (!SE.hasLoopInvariantBackedgeTakenCount(L)) {
1081     LLVM_DEBUG(dbgs() << "ARMHWLoops: No BETC\n");
1082     return false;
1083   }
1084 
1085   const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
1086   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
1087     LLVM_DEBUG(dbgs() << "ARMHWLoops: Uncomputable BETC\n");
1088     return false;
1089   }
1090 
1091   const SCEV *TripCountSCEV =
1092     SE.getAddExpr(BackedgeTakenCount,
1093                   SE.getOne(BackedgeTakenCount->getType()));
1094 
1095   // We need to store the trip count in LR, a 32-bit register.
1096   if (SE.getUnsignedRangeMax(TripCountSCEV).getBitWidth() > 32) {
1097     LLVM_DEBUG(dbgs() << "ARMHWLoops: Trip count does not fit into 32bits\n");
1098     return false;
1099   }
1100 
1101   // Making a call will trash LR and clear LO_BRANCH_INFO, so there's little
1102   // point in generating a hardware loop if that's going to happen.
1103   auto MaybeCall = [this](Instruction &I) {
1104     const ARMTargetLowering *TLI = getTLI();
1105     unsigned ISD = TLI->InstructionOpcodeToISD(I.getOpcode());
1106     EVT VT = TLI->getValueType(DL, I.getType(), true);
1107     if (TLI->getOperationAction(ISD, VT) == TargetLowering::LibCall)
1108       return true;
1109 
1110     // Check if an intrinsic will be lowered to a call and assume that any
1111     // other CallInst will generate a bl.
1112     if (auto *Call = dyn_cast<CallInst>(&I)) {
1113       if (isa<IntrinsicInst>(Call)) {
1114         if (const Function *F = Call->getCalledFunction())
1115           return isLoweredToCall(F);
1116       }
1117       return true;
1118     }
1119 
1120     // FPv5 provides conversions between integer, double-precision,
1121     // single-precision, and half-precision formats.
1122     switch (I.getOpcode()) {
1123     default:
1124       break;
1125     case Instruction::FPToSI:
1126     case Instruction::FPToUI:
1127     case Instruction::SIToFP:
1128     case Instruction::UIToFP:
1129     case Instruction::FPTrunc:
1130     case Instruction::FPExt:
1131       return !ST->hasFPARMv8Base();
1132     }
1133 
1134     // FIXME: Unfortunately the approach of checking the Operation Action does
1135     // not catch all cases of Legalization that use library calls. Our
1136     // Legalization step categorizes some transformations into library calls as
1137     // Custom, Expand or even Legal when doing type legalization. So for now
1138     // we have to special case for instance the SDIV of 64bit integers and the
1139     // use of floating point emulation.
1140     if (VT.isInteger() && VT.getSizeInBits() >= 64) {
1141       switch (ISD) {
1142       default:
1143         break;
1144       case ISD::SDIV:
1145       case ISD::UDIV:
1146       case ISD::SREM:
1147       case ISD::UREM:
1148       case ISD::SDIVREM:
1149       case ISD::UDIVREM:
1150         return true;
1151       }
1152     }
1153 
1154     // Assume all other non-float operations are supported.
1155     if (!VT.isFloatingPoint())
1156       return false;
1157 
1158     // We'll need a library call to handle most floats when using soft.
1159     if (TLI->useSoftFloat()) {
1160       switch (I.getOpcode()) {
1161       default:
1162         return true;
1163       case Instruction::Alloca:
1164       case Instruction::Load:
1165       case Instruction::Store:
1166       case Instruction::Select:
1167       case Instruction::PHI:
1168         return false;
1169       }
1170     }
1171 
1172     // We'll need a libcall to perform double precision operations on a single
1173     // precision only FPU.
1174     if (I.getType()->isDoubleTy() && !ST->hasFP64())
1175       return true;
1176 
1177     // Likewise for half precision arithmetic.
1178     if (I.getType()->isHalfTy() && !ST->hasFullFP16())
1179       return true;
1180 
1181     return false;
1182   };
1183 
1184   auto IsHardwareLoopIntrinsic = [](Instruction &I) {
1185     if (auto *Call = dyn_cast<IntrinsicInst>(&I)) {
1186       switch (Call->getIntrinsicID()) {
1187       default:
1188         break;
1189       case Intrinsic::set_loop_iterations:
1190       case Intrinsic::test_set_loop_iterations:
1191       case Intrinsic::loop_decrement:
1192       case Intrinsic::loop_decrement_reg:
1193         return true;
1194       }
1195     }
1196     return false;
1197   };
1198 
1199   // Scan the instructions to see if there's any that we know will turn into a
1200   // call or if this loop is already a low-overhead loop.
1201   auto ScanLoop = [&](Loop *L) {
1202     for (auto *BB : L->getBlocks()) {
1203       for (auto &I : *BB) {
1204         if (MaybeCall(I) || IsHardwareLoopIntrinsic(I)) {
1205           LLVM_DEBUG(dbgs() << "ARMHWLoops: Bad instruction: " << I << "\n");
1206           return false;
1207         }
1208       }
1209     }
1210     return true;
1211   };
1212 
1213   // Visit inner loops.
1214   for (auto Inner : *L)
1215     if (!ScanLoop(Inner))
1216       return false;
1217 
1218   if (!ScanLoop(L))
1219     return false;
1220 
1221   // TODO: Check whether the trip count calculation is expensive. If L is the
1222   // inner loop but we know it has a low trip count, calculating that trip
1223   // count (in the parent loop) may be detrimental.
1224 
1225   LLVMContext &C = L->getHeader()->getContext();
1226   HWLoopInfo.CounterInReg = true;
1227   HWLoopInfo.IsNestingLegal = false;
1228   HWLoopInfo.PerformEntryTest = true;
1229   HWLoopInfo.CountType = Type::getInt32Ty(C);
1230   HWLoopInfo.LoopDecrement = ConstantInt::get(HWLoopInfo.CountType, 1);
1231   return true;
1232 }
1233 
1234 static bool canTailPredicateInstruction(Instruction &I, int &ICmpCount) {
1235   // We don't allow icmp's, and because we only look at single block loops,
1236   // we simply count the icmps, i.e. there should only be 1 for the backedge.
1237   if (isa<ICmpInst>(&I) && ++ICmpCount > 1)
1238     return false;
1239 
1240   if (isa<FCmpInst>(&I))
1241     return false;
1242 
1243   // We could allow extending/narrowing FP loads/stores, but codegen is
1244   // too inefficient so reject this for now.
1245   if (isa<FPExtInst>(&I) || isa<FPTruncInst>(&I))
1246     return false;
1247 
1248   // Extends have to be extending-loads
1249   if (isa<SExtInst>(&I) || isa<ZExtInst>(&I) )
1250     if (!I.getOperand(0)->hasOneUse() || !isa<LoadInst>(I.getOperand(0)))
1251       return false;
1252 
1253   // Truncs have to be narrowing-stores
1254   if (isa<TruncInst>(&I) )
1255     if (!I.hasOneUse() || !isa<StoreInst>(*I.user_begin()))
1256       return false;
1257 
1258   return true;
1259 }
1260 
1261 // To set up a tail-predicated loop, we need to know the total number of
1262 // elements processed by that loop. Thus, we need to determine the element
1263 // size and:
1264 // 1) it should be uniform for all operations in the vector loop, so we
1265 //    e.g. don't want any widening/narrowing operations.
1266 // 2) it should be smaller than i64s because we don't have vector operations
1267 //    that work on i64s.
1268 // 3) we don't want elements to be reversed or shuffled, to make sure the
1269 //    tail-predication masks/predicates the right lanes.
1270 //
1271 static bool canTailPredicateLoop(Loop *L, LoopInfo *LI, ScalarEvolution &SE,
1272                                  const DataLayout &DL,
1273                                  const LoopAccessInfo *LAI) {
1274   PredicatedScalarEvolution PSE = LAI->getPSE();
1275   int ICmpCount = 0;
1276   int Stride = 0;
1277 
1278   LLVM_DEBUG(dbgs() << "tail-predication: checking allowed instructions\n");
1279   SmallVector<Instruction *, 16> LoadStores;
1280   for (BasicBlock *BB : L->blocks()) {
1281     for (Instruction &I : BB->instructionsWithoutDebug()) {
1282       if (isa<PHINode>(&I))
1283         continue;
1284       if (!canTailPredicateInstruction(I, ICmpCount)) {
1285         LLVM_DEBUG(dbgs() << "Instruction not allowed: "; I.dump());
1286         return false;
1287       }
1288 
1289       Type *T  = I.getType();
1290       if (T->isPointerTy())
1291         T = T->getPointerElementType();
1292 
1293       if (T->getScalarSizeInBits() > 32) {
1294         LLVM_DEBUG(dbgs() << "Unsupported Type: "; T->dump());
1295         return false;
1296       }
1297 
1298       if (isa<StoreInst>(I) || isa<LoadInst>(I)) {
1299         Value *Ptr = isa<LoadInst>(I) ? I.getOperand(0) : I.getOperand(1);
1300         int64_t NextStride = getPtrStride(PSE, Ptr, L);
1301         // TODO: for now only allow consecutive strides of 1. We could support
1302         // other strides as long as it is uniform, but let's keep it simple for
1303         // now.
1304         if (Stride == 0 && NextStride == 1) {
1305           Stride = NextStride;
1306           continue;
1307         }
1308         if (Stride != NextStride) {
1309           LLVM_DEBUG(dbgs() << "Different strides found, can't "
1310                                "tail-predicate\n.");
1311           return false;
1312         }
1313       }
1314     }
1315   }
1316 
1317   LLVM_DEBUG(dbgs() << "tail-predication: all instructions allowed!\n");
1318   return true;
1319 }
1320 
1321 bool ARMTTIImpl::preferPredicateOverEpilogue(Loop *L, LoopInfo *LI,
1322                                              ScalarEvolution &SE,
1323                                              AssumptionCache &AC,
1324                                              TargetLibraryInfo *TLI,
1325                                              DominatorTree *DT,
1326                                              const LoopAccessInfo *LAI) {
1327   if (DisableTailPredication)
1328     return false;
1329 
1330   // Creating a predicated vector loop is the first step for generating a
1331   // tail-predicated hardware loop, for which we need the MVE masked
1332   // load/stores instructions:
1333   if (!ST->hasMVEIntegerOps())
1334     return false;
1335 
1336   // For now, restrict this to single block loops.
1337   if (L->getNumBlocks() > 1) {
1338     LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: not a single block "
1339                          "loop.\n");
1340     return false;
1341   }
1342 
1343   assert(L->empty() && "preferPredicateOverEpilogue: inner-loop expected");
1344 
1345   HardwareLoopInfo HWLoopInfo(L);
1346   if (!HWLoopInfo.canAnalyze(*LI)) {
1347     LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not "
1348                          "analyzable.\n");
1349     return false;
1350   }
1351 
1352   // This checks if we have the low-overhead branch architecture
1353   // extension, and if we will create a hardware-loop:
1354   if (!isHardwareLoopProfitable(L, SE, AC, TLI, HWLoopInfo)) {
1355     LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not "
1356                          "profitable.\n");
1357     return false;
1358   }
1359 
1360   if (!HWLoopInfo.isHardwareLoopCandidate(SE, *LI, *DT)) {
1361     LLVM_DEBUG(dbgs() << "preferPredicateOverEpilogue: hardware-loop is not "
1362                          "a candidate.\n");
1363     return false;
1364   }
1365 
1366   return canTailPredicateLoop(L, LI, SE, DL, LAI);
1367 }
1368 
1369 
1370 void ARMTTIImpl::getUnrollingPreferences(Loop *L, ScalarEvolution &SE,
1371                                          TTI::UnrollingPreferences &UP) {
1372   // Only currently enable these preferences for M-Class cores.
1373   if (!ST->isMClass())
1374     return BasicTTIImplBase::getUnrollingPreferences(L, SE, UP);
1375 
1376   // Disable loop unrolling for Oz and Os.
1377   UP.OptSizeThreshold = 0;
1378   UP.PartialOptSizeThreshold = 0;
1379   if (L->getHeader()->getParent()->hasOptSize())
1380     return;
1381 
1382   // Only enable on Thumb-2 targets.
1383   if (!ST->isThumb2())
1384     return;
1385 
1386   SmallVector<BasicBlock*, 4> ExitingBlocks;
1387   L->getExitingBlocks(ExitingBlocks);
1388   LLVM_DEBUG(dbgs() << "Loop has:\n"
1389                     << "Blocks: " << L->getNumBlocks() << "\n"
1390                     << "Exit blocks: " << ExitingBlocks.size() << "\n");
1391 
1392   // Only allow another exit other than the latch. This acts as an early exit
1393   // as it mirrors the profitability calculation of the runtime unroller.
1394   if (ExitingBlocks.size() > 2)
1395     return;
1396 
1397   // Limit the CFG of the loop body for targets with a branch predictor.
1398   // Allowing 4 blocks permits if-then-else diamonds in the body.
1399   if (ST->hasBranchPredictor() && L->getNumBlocks() > 4)
1400     return;
1401 
1402   // Scan the loop: don't unroll loops with calls as this could prevent
1403   // inlining.
1404   unsigned Cost = 0;
1405   for (auto *BB : L->getBlocks()) {
1406     for (auto &I : *BB) {
1407       // Don't unroll vectorised loop. MVE does not benefit from it as much as
1408       // scalar code.
1409       if (I.getType()->isVectorTy())
1410         return;
1411 
1412       if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
1413         if (const Function *F = cast<CallBase>(I).getCalledFunction()) {
1414           if (!isLoweredToCall(F))
1415             continue;
1416         }
1417         return;
1418       }
1419 
1420       SmallVector<const Value*, 4> Operands(I.value_op_begin(),
1421                                             I.value_op_end());
1422       Cost += getUserCost(&I, Operands, TargetTransformInfo::TCK_CodeSize);
1423     }
1424   }
1425 
1426   LLVM_DEBUG(dbgs() << "Cost of loop: " << Cost << "\n");
1427 
1428   UP.Partial = true;
1429   UP.Runtime = true;
1430   UP.UpperBound = true;
1431   UP.UnrollRemainder = true;
1432   UP.DefaultUnrollRuntimeCount = 4;
1433   UP.UnrollAndJam = true;
1434   UP.UnrollAndJamInnerLoopThreshold = 60;
1435 
1436   // Force unrolling small loops can be very useful because of the branch
1437   // taken cost of the backedge.
1438   if (Cost < 12)
1439     UP.Force = true;
1440 }
1441 
1442 bool ARMTTIImpl::useReductionIntrinsic(unsigned Opcode, Type *Ty,
1443                                        TTI::ReductionFlags Flags) const {
1444   assert(isa<VectorType>(Ty) && "Expected Ty to be a vector type");
1445   unsigned ScalarBits = Ty->getScalarSizeInBits();
1446   if (!ST->hasMVEIntegerOps())
1447     return false;
1448 
1449   switch (Opcode) {
1450   case Instruction::FAdd:
1451   case Instruction::FMul:
1452   case Instruction::And:
1453   case Instruction::Or:
1454   case Instruction::Xor:
1455   case Instruction::Mul:
1456   case Instruction::FCmp:
1457     return false;
1458   case Instruction::ICmp:
1459   case Instruction::Add:
1460     return ScalarBits < 64 &&
1461            (ScalarBits * cast<VectorType>(Ty)->getNumElements()) % 128 == 0;
1462   default:
1463     llvm_unreachable("Unhandled reduction opcode");
1464   }
1465   return false;
1466 }
1467