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